难度设置集中在javascript中新创建的对象上 [英] Difficulty setting focus on newly created object in javascript

查看:58
本文介绍了难度设置集中在javascript中新创建的对象上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,与先前的问题有关,但请原谅我的幼稚javascript方式.基本上,我现在想在将文本输入添加到DOM时自动使其成为焦点.我的一部分认为我可能会尝试在该对象存在之前为其添加焦点,但是我不太确定如何解决该问题.现在,这是我的相关代码:

So, related to an earlier question, but forgive me for my naive javascript ways. Basically I now want to automatically bring a text input into focus when it is added to the DOM. Part of me thinks that I might be trying to add focus to the object before it exists, but I'm not quite sure how I would go about fixing it. Right now this is my relevant code:

var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";

this.parentNode.replaceChild(searchWrapper, this);
document.getElementById("search-wrapper").focus();

但是效果不佳.我应该将焦点设置为replaceChild的回调,还是有其他方法可以做到这一点?

But it's not quite working. Should I be setting focus as a callback on replaceChild, or is there some other way to do this?

推荐答案

尝试以下操作:

实时演示

var searchOrig = document.getElementById("search-wrapper"); 

var searchWrapper = document.createElement("div");
searchWrapper.id = "search-wrapper";
searchWrapper.setAttribute('tabindex', '0'); 

searchOrig.parentElement.replaceChild(searchWrapper, searchOrig);
document.getElementById("search-wrapper").focus();

这篇关于难度设置集中在javascript中新创建的对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆