简体   繁体   English

在锚点单击时切换输入字段

[英]toggle input field on an anchor click

I'm trying to make it so when the user clicks "Link" then it scrolls down to the input field "a" and toggles it without having to click.我试图做到这一点,当用户单击“链接”时,它会向下滚动到输入字段“a”并切换它而无需单击。 I'm already making use of jQuery so perhaps it should handle scrolling as well, however I'm unsure how to deal with toggling (perhaps focusing on is the right terminology) an input field automatically.我已经在使用 jQuery,所以也许它也应该处理滚动,但是我不确定如何自动处理切换(也许专注于正确的术语)输入字段。 Note: I omitted all other code for readability.注意:为了可读性,我省略了所有其他代码。

<a href="#view" class="button">Link</a>

<div id="view">
<input type="text" id="a" name="a">
</div>

Not sure what you mean by 'toggle', but you can use focus to move the cursor (in)to the input field.不确定“切换”是什么意思,但您可以使用focus将光标(移入)移动到输入字段。 Here's a snippet where the input field is out of sight.这是输入字段看不见的片段。 The handling is done using event delegation .处理是使用事件委托完成的。

 document.addEventListener(`click`, handle); function handle(evt) { if (evt.target.id === `view`) { // if you click from a href element, you have to prevent // the default action of the click. May be advisable to // use a button here. evt.preventDefault(); const inpVw = document.querySelector(`#a`); // focusing automatically scrolls to the field inpVw.focus(); inpVw.setAttribute(`placeholder`, `Feel free to type`); } }
 #viewInput { margin-top: 120vh; }
 <a id="view" href="#">Link</a> <p id="viewInput"> <input type="text" id="a" name="a"> </p>

Add an empty anchor tag:添加一个空的锚标签:

<div id="view">
<input type="text" id="a" name="a">
<a name="myawesomeanchour"></a>
</div>

then add the event handler to the 'Link' button:然后将事件处理程序添加到“链接”按钮:

var myawesometag = $("a[name='myawesomeanchour']");
$('html,body').animate({scrollTop:myawesometag.offset().top},'slow');
$('#a').toggle();

remove the toggle line if the toggle isn't still required.如果仍然不需要切换,请移除切换线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM