2017-01-02 6 views
3

Что я хочу сделать, это автофокус на модальном виде. Объяснить это немного дальше. Я хочу, чтобы, когда я нажимаю на свое изображение на своей веб-странице, и он открывает модальный вид, он должен автоматически фокусироваться на модальности, позволяя мне прокручивать вверх и вниз без меня, чтобы щелкнуть по изображению, чтобы привлечь его к фокусу прокручивать вверх и вниз с помощью клавиатуры.Автофокус на Modal View

http://imgur.com/a/hG0CF

http://imgur.com/a/W9Erw

http://imgur.com/a/Ijcn5

Последующие я дал ссылки выше, чтобы картины. Надеюсь, теперь это станет проще. Приветствия

HTML

<!DOCTYPE html> 
<html> 
<head> 
    <title> 
    Advise Column 
    </title> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> 
    <link rel="stylesheet" type="text/css" href="Modal.css"> 
    <link href="https://fonts.googleapis.com/css?family=Quattrocento|Risque|Unkempt" rel="stylesheet"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
</head> 
<body> 
<br/> 
<div class="container"> 
    <div class="row"> 
     <div class="panel panel-info"> 
      <div class="panel-heading"><h1 id="top-hd-01" class="page-header">PICK A SENSEI!</h1></div> 
     </div> 
    </div> 
</div> 
<div class="container"> 
    <div class="row"> 
     <figure class="col-xs-12 col-sm-12 col-md-4 col-lg-4 img-placement"> 
      <img src="Batman.jpg" alt="BATMAN" class="advise-page-img-sizing adv-page-img-modalling" id="adv-page-img-01"> 
      <figcaption class="img-captioning">BATMAN</figcaption> 
     </figure> 
     <figure class="col-xs-12 col-sm-12 col-md-4 col-lg-4 img-placement"> 
      <img src="Robin.jpg" alt="ROBINS" class="advise-page-img-sizing adv-page-img-modalling" id="adv-page-img-02"> 
      <figcaption class="img-captioning">ROBIN</figcaption> 
     </figure> 
     <figure class="col-xs-12 col-sm-12 col-md-4 col-lg-4 img-placement"> 
      <img src="Joker.jpg" alt="JOKER" class="advise-page-img-sizing adv-page-img-modalling" id="adv-page-img-03"> 
      <figcaption class="img-captioning">JOKER</figcaption> 
     </figure> 
    </div> 
</div> 
<!-- The Modal --> 
<div class="modal" id="myModal"> 

    <!-- The Close Button --> 
    <span class="close" id="modal-cross-button" onclick="document.getElementById('myModal').style.display='none'">&times;</span> 

    <!-- Modal Content (The Image) --> 
    <img class="modal-content" id="modal-adv-page-img"> 
    <!-- Modal Caption (Image Text) --> 
    <div id="caption"></div> 
</div> 

<script src="Modal.js" type="text/javascript"></script> 
</body> 
</html> 

CSS

#top-hd-01 
{ 
    font-family: 'Unkempt', cursive; 
} 

.img-placement 
{ 
    display: block; 
    text-align: center; 
    /*cursor: pointer;*/ 
} 

.advise-page-img-sizing 
{ 
    height: 250px; 
    width: 350px; 
} 

.img-captioning 
{ 
    font-size: 35px; 
    font-family: 'Risque', cursive; 
    text-align: center; 
    margin-top: 10px; 

} 


/* Style the Image Used to Trigger the Modal */ 
.adv-page-img-modalling { 
    border-radius: 5px; 
    cursor: pointer; 
    transition: 0.3s; 
} 

.adv-page-img-modalling:hover {opacity: 0.7;} 

/* The Modal (background) */ 
.modal { 
    display: none; /* Hidden by default */ 
    position: fixed; /* Stay in place */ 
    z-index: 1; /* Sit on top */ 
    padding-top: 100px; /* Location of the box */ 
    left: 0; 
    top: 0; 
    width: 100%; /* Full width */ 
    height: 100%; /* Full height */ 
    overflow: auto; /* Enable scroll if needed */ 
    background-color: rgb(0,0,0); /* Fallback color */ 
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */ 
} 

/* Modal Content (Image) */ 
.modal-content { 
    margin: auto; 
    display: block; 
    width: 80%; 
    padding: 20px; 
    /*height: 100%;*/ 
    /* max-height: 450px; 
    max-width: 700px;*/ 
} 

#modal-cross-button 
{ 
    position: fixed; 
} 

.sensei-answers, .sensei-questions, .sensei-quote 
{ 
    font-family: 'Quattrocento', serif; 
} 

.sensei-questions 
{ 
    font-size: 28px; 
} 

.sensei-answers 
{ 
    font-size: 22px; 
    color: darkblue; 
} 

.sensei-quote 
{ 
    font-size: 20px; 
    text-align: center; 
    color: #ff751b; 
} 

/* Caption of Modal Image (Image Text) - Same Width as the Image */ 
#caption { 
    margin: auto; 
    display: block; 
    width: 80%; 
    max-width: 700px; 
    text-align: center; 
    color: #ccc; 
    padding: 10px 0; 
    height: 150px; 
} 

/* Add Animation - Zoom in the Modal */ 
.modal-content, #caption { 
    -webkit-animation-name: zoom; 
    -webkit-animation-duration: 0.6s; 
    animation-name: zoom; 
    animation-duration: 0.6s; 
} 

@-webkit-keyframes zoom { 
    from {-webkit-transform:scale(0)} 
    to {-webkit-transform:scale(1)} 
} 

@keyframes zoom { 
    from {transform:scale(0)} 
    to {transform:scale(1)} 
} 

/* The Close Button */ 
.close { 
    position: absolute; 
    top: 15px; 
    right: 35px; 
    color: #f1f1f1; 
    font-size: 40px; 
    font-weight: bold; 
    transition: 0.3s; 
} 

.close:hover, 
.close:focus { 
    color: #bbb; 
    text-decoration: none; 
    cursor: pointer; 
} 

/* 100% Image Width on Smaller Screens */ 
@media only screen and (max-width: 700px){ 
    .modal-content { 
     width: 100%; 
    } 
} 

JavaScript

// Get the modal 
var modal = document.getElementById("myModal"); 

// Get the image and insert it inside the modal - use its "alt" text as a caption 
var modalImg = document.getElementById("modal-adv-page-img"); 

var img1 = document.getElementById("adv-page-img-01") 
var img2 = document.getElementById("adv-page-img-02") 
var img3 = document.getElementById("adv-page-img-03") 

var captionText = document.getElementById("caption"); 

img1.onclick = function(){ 
    modal.style.display = "block"; 
    modalImg.src = this.src; 
    captionText.innerHTML = this.alt; 
} 
img2.onclick = function(){ 
    modal.style.display = "block"; 
    modalImg.src = this.src; 
    captionText.innerHTML = this.alt; 
} 
img3.onclick = function(){ 
    modal.style.display = "block"; 
    modalImg.src = this.src; 
    captionText.innerHTML = this.alt; 
} 


// Get the <span> element that closes the modal 
var span = document.getElementsByClassName("close")[0]; 

// When the user clicks on <span> (x), close the modal 
span.onclick = function() { 
    modal.style.display = "none"; 
} 

ответ

0

Атрибут autofocus не будет работать в этом случае, так как это будет срабатывать при загрузке страницы. Однако вы можете легко решить эту проблему с помощью JavaScript.

document.getElementById('modal').focus(); // vanilla JS 
$('#modal').focus(); // jQuery 

Обязательно запускайте одну из этих функций, как только модаль будет открыт.

+0

Я попытался как ваниль JS и JQuery. Я попытался запустить vanilla JS в функции img1.onclick после отображения модальности, используя modal.display = block. С JQuery я попытался сделать то же самое. Я использовал функцию предупреждения, чтобы убедиться, что мои триггеры работают. Не работает. Я буду продолжать пытаться, у меня такое чувство, что я делаю что-то глупое, поэтому оно не работает так, как хотелось бы. –

0

Вы можете попробовать это:

$("#myModal").on('shown.bs.modal', function() { 
     $(this).focus(); 
}); 
+0

Не могли бы вы рассказать, для чего предназначен 'показанный.bs.modal'. Я предположил, что «показанный.bs.modal» будет отображаться или показываться модальный. Я попытался использовать вашу функцию, но я не получил положительного результата. –

+0

Извините, я думал, что вы используете bootstrap modal (я видел '# myModal' и предполагаю, что это был загрузочный файл по умолчанию). Это не относится к тому, что вы делаете. Вы пытались применить фокус в одном из элементов внутри модального? –

+0

О, я посмотрю, как это сделать, и посмотрите, работает ли это. B/c Я использую bootstrap. Также я попытаюсь сосредоточиться на каком-то элементе внутри модального следующего. –