Javascript弹出警示框时聚焦于指定的div

6
我想要做的是创建一系列的弹出警报窗口,用作学习网站功能的教程。这些弹出窗口将依次出现,解释网站中每个“div”的作用。当弹出窗口出现时,我希望引用的“div”获得焦点(置于前景),以使其更加可见。
代码如下,显然它并不起作用:
var someDiv = document.getElementById('someID');
someDiv.focus();

alert("Message explaining functionality");

我做错了什么?

1
alert()div如何同时具有focus?您可以使用消息调用alert(),然后在alert()关闭时调用元素上的focus - guest271314
1
如果您想要共享焦点,警报是错误的机制。所有主要的浏览器实现都会阻止与网站的交互,而且它看起来很糟糕。您最好实现自己的通知框,并将其定位在您提供信息的每个元素旁边。 - ste2425
1
没有人喜欢警报。 - Mikey
2个回答

6
为了使一个 div 具有可聚焦性,你需要使用 tabindex
<div id='someID' tabindex='1'>MY DIV TEST</div>

尝试使用setTimeout给它一点时间来focus

注意:我建议使用比alert()更灵活的模态插件。

希望这可以帮助你。

var someDiv = document.getElementById('someID');
someDiv.focus();

setTimeout(function(){
  alert("Message explaining functionality");
},10)
<div id='someID' tabindex='1'>MY DIV TEST</div>


1
你可以尝试使用这个来制作你的教程。我之前做过类似的事情。在这里查看项目

$(document).ready(function() {

      // Initialize the plugin
      $('#my_popup').popup();

    });
    
<button class="my_popup_open">Tutorial</button>
<!-- Content of popup -->
<div id="my_popup">
I'm Tutorial
<button class="my_popup_close">Close</button></div>

  <!-- Include jQuery -->
  <script src="https://code.jquery.com/jquery-1.8.2.min.js"></script>

  <!-- Include jQuery Popup Overlay -->
  <script src="https://cdn.rawgit.com/vast-engineering/jquery-popup-overlay/1.7.13/jquery.popupoverlay.js"></script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接