【问题标题】:Focus on form field after animation动画后关注表单域
【发布时间】:2012-04-06 23:52:48
【问题描述】:

我想在短 d3 动画中显示,并在完成后自动选择/聚焦表单字段以获取用户输入。

似乎最好通过链接函数来完成。我尝试使用在加载时选择表单字段(“signup”、“inputname”)的javascript函数focus(),但这不起作用。

动画完成后如何自动选择表单域?

d3.js:

<script>
selectReady = d3.selectAll("#ready")
    .on("mouseover", function(){d3.select(this).style("color", "red");})
    .on("mouseout", function(){d3.select(this).style("color", "black");})           
    .on("mousedown", animateDisplay); //starts animation with a mousepress

function animateDisplay(){
    d3.selectAll("#Display")
        .transition()
        .delay(200)            
        .duration(1000)             
        .style("color","white") // changes Display to white
        .each("end",selectForm);
};

function selectForm(){
    d3.select("#inputname")
        .focus(); // remove() works here
};  

</script>

HTML:

<html>
<head>
<script type="text/javascript"src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<p id="ready">Click when ready<p></th>
<p id='Display'>A</p>
<p id='Display'>B</p>
<p id='Display'>C</p>

<form name="signup" id="signup" method="post" action="#">   
    <table> 
        <tr>        
        <td colspan="2" class="labelcell"><label for="name">Name</label></td>   
        <td colspan="2" class="fieldcell">      
            <input type="text" name="inputname" id="inputname" tabindex="1" />  
        </td>   
        </tr>
    </table>
</form>
</body>
</html>

【问题讨论】:

  • 为什么在keydown上使用?为什么不只是.each("end",function () { if (this is last frame) document.response.inputname.focus()});
  • 这很好——但是,这也不起作用。我想知道这是否是焦点()的问题
  • 我已将 d3 添加到此 fiddle 中,您可以添加代码和 html 以显示示例吗?
  • 编辑问题以便于摆弄(包括所有代码)

标签: javascript jquery d3.js


【解决方案1】:

很清楚DEMO

d3.select("#inputname").focus is not a function
http://fiddle.jshell.net/mplungjan/JfvbD/show/
Line 41

给你

我改成了这个

<p id='DisplayA' class="disp">A</p>
<p id='DisplayB' class="disp">B</p>
<p id='DisplayC' class="disp">C</p>

所以我可以使用这个:

d3.selectAll(".disp")

并有代码

function selectForm(){
  if (this.id!="DisplayC") return;
  document.getElementById('inputname').focus();  
}; 

【讨论】:

  • 非常感谢! document.getElementById('inputname').focus() 函数特别有用。
【解决方案2】:

使用selection.node访问底层DOM元素,然后element.focus

d3.select("#inputname").node().focus()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-20
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多