Ser*_*Amo 13 html javascript jquery focus
假设我有下一个标记:
<div id="content">
<div id="firstP"><p>First paragraph</p></div>
<div id="secondP"><p>Second paragraph</p></div>
<div id="thirdP"><p>Third paragraph</p></div>
<div id="fourthP"><p>Fourth paragraph</p></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我想用Javascript添加一个新的div并专注于这个新元素.焦点没有做任何事情.
function addParagraph() {
var html = "<div id=\"newP\"><p>New paragraph</p></div>";
$("#content").append(html);
$("#newP").focus();
}
Run Code Online (Sandbox Code Playgroud)
任何的想法?
小智 50
我认为主要答案是错误的.DIV和P标签可以获得焦点,您可以为它们指定tabindex属性.即
<div class="someclass" tabindex="100">
Run Code Online (Sandbox Code Playgroud)
指定tabindex后,您可以选中这些元素或使用.focus()移动焦点.
使用scrollTo插件在这里看起来有点过分.
nic*_*ckf 17
您的代码没有问题,只是段落或div标签无法获得焦点.只能将焦点放在可以与之交互的事物上,例如链接,输入元素,textareas等.
要将窗口滚动到此新添加的元素,可以使用ScrollTo等插件.
另外,您的代码可以简化一下:
var html = "<div id=\"newP\"><p>New paragraph</p></div>";
$("#content").append(html);
$("#newP p").focus();
var html = "<div id=\"newP\"><p>New paragraph</p></div>";
$(html)
.appendTo('#content')
.focus() // or scrollTo(), now...
;
Run Code Online (Sandbox Code Playgroud)
此代码将避免依赖于其他插件,并允许您在任何元素上使用它.
$('html, body').animate({ scrollTop: $("#newP").offset().top }, 500);
Run Code Online (Sandbox Code Playgroud)