# 已添加到 url 时,如何使用 javascript 或 jquery 将焦点设置在 div 上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11030503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:07:09  来源:igfitidea点击:

how to set focus on a div using javascript or jquery when # already added in url?

javascriptjqueryhtmlfocussetfocus

提问by Jimesh Gajera

I want to set focus on particular div using jquery or javascript. i have just use document.getElementById("pack_0").focus();in that 'pack_0' is my div id but it doesn't work. I notice that '#' is already added in my url because of some popup coding, so my url is 'http://localhost/website/book#'

我想使用 jquery 或 javascript 将焦点设置在特定的 div 上。我刚刚使用document.getElementById("pack_0").focus();了 'pack_0' 是我的 div id,但它不起作用。我注意到由于一些弹出式编码,我的 url 中已经添加了 '#',所以我的 url 是 'http://localhost/website/book#'

So, can any one help me for force fully focus on div when # in url?

那么,当 # in url 时,任何人都可以帮助我完全专注于 div 吗?

Thanks in advance.

提前致谢。

回答by Anthony Grist

From the question, I think what you actually mean by "focus the div" is "change the window's vertical scroll position so the div is visible". If that is the case, you can use the following bit of jQuery code:

从这个问题来看,我认为“聚焦 div”的实际意思是“更改窗口的垂直滚动位置,使 div 可见”。如果是这种情况,您可以使用以下 jQuery 代码:

$(window).scrollTop($('#pack_0').offset().top);

回答by LukeAmerica2020

Anthony Grist's assumption is likely correct in your case. However, it may help others searching on this topic to know that if the desired object of focusis a DIV, that DIV should have a tabindexset, e.g., tabindex="9999". Otherwise, most browsers will not assign the focus.

Anthony Grist 的假设在您的情况下可能是正确的。但是,它可以帮助搜索此主题的其他人了解,如果所需的焦点对象是 DIV,则该 DIV 应设置tabindex,例如,tabindex="9999"。否则,大多数浏览器不会分配焦点。

回答by Digisha

To set focus to div first we need to define tabindex for particular div like as below

要首先将焦点设置为 div,我们需要为特定的 div 定义 tabindex,如下所示

<div class="leftbar-btn-module" tabindex="-1">'Content'</div>

And jquery to set focus

和 jquery 设置焦点

jQuery(".leftbar-btn-module").attr("tabindex",-1).focus();