【问题标题】:Setting focus to a div after show显示后将焦点设置为 div
【发布时间】:2013-07-08 16:21:22
【问题描述】:

我试图将焦点放在调用 .show() 函数后显示的隐藏 div 上。我尝试了几件事,包括 show().focus() 或将其拆分为

$(".messageDisplayArea").show();
$("#message_display_area").focus();

div 出现了,但页面没有将焦点转移到它。

<script>
    function showMessage(id, row) {
            selectRow(row);         
            $(".messageDisplayArea").show();        
            $("#message_display_area").focus();
    }

</script>


<div class="messageDisplayArea" id="message_display_area" style="display: none;">

<p> Test Test Test </p>

</div>

我错过了什么?它所在的页面相当大,div 出现在页面底部。我想让浏览器跳下来,把新的 div 放在焦点上

【问题讨论】:

  • 您希望将焦点放在div 元素上是什么意思?
  • 也许我误解了 .focus() 函数。我想要做的是真正关注这个出现的新 div。就像让浏览器跳转到 div 一样,因为它出现在屏幕底部,用户甚至不知道它在那里,直到他们向下滚动

标签: javascript html focus show-hide


【解决方案1】:

替换这一行:

$("#message_display_area").focus();

用这一行:

window.location.hash = "message_display_area";

【讨论】:

  • 非常感谢,这正是我想要的!简短、甜美、简单
【解决方案2】:

就你给我们的代码而言,你所拥有的应该可以工作,就像这个小提琴一样。

http://jsfiddle.net/SuERE/

http://jsfiddle.net/SuERE/1/

HTML:

<button type="button">Show and Focus</button>
<div style='height:700px'></div>
<input type="text" id="input" style='display:none;'/>

Javascript:

$("button").on("click",function(){
   $("#input").show();
    $("#input").focus();
});

【讨论】:

  • 感谢您抽出宝贵时间发帖并提供帮助!
【解决方案3】:

Focus 并不意味着您的页面滚动到该元素,实际上通常用于表单控件以获取光标。

您实际上需要的是一个 scrollToElement() 函数,它计算新创建的 div 的页面偏移量并将页面滚动到该位置,这里描述了一个很好的方法:jQuery scroll to element

【讨论】:

  • 感谢您的发帖,感谢您的宝贵时间!
【解决方案4】:

您可以做的另一件事是将tabindex 属性添加到 div 元素。这将使focus 方法能够执行并找到它并自动移动到它。

&lt;div id="message-display-area" tabindex=1000&gt;...&lt;/div&gt;

JSFiddle 表明它工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-26
    • 2011-10-08
    • 2016-01-19
    • 1970-01-01
    • 2014-09-22
    • 2016-12-06
    • 2012-10-27
    • 2022-07-19
    相关资源
    最近更新 更多