簡體   English   中英

單擊鏈接並轉到輸入

[英]Click on a link and go to a input

我想鏈接到輸入。 我當前的鏈接示例有效(將我帶到設置了id的區域),但是我真正想要的是當用戶單擊鏈接以將他帶到輸入的確切位置時,可以立即鍵入。

<input type="text" id="search" name="search">

<a href="#search">
<img src="http://www.example.com/images/something.jpg" alt="">
</a>

如果沒有JQuery / JavaScript,這甚至可以實現嗎? 請以您可以想象的任何方式發布解決方案。 搜尋了一段時間,找不到答案。

無需使用javascript:使用label代替帶有for屬性的鏈接

<input type="text" id="search" name="search">

<label for="search">
   <img src="http://www.example.com/images/something.jpg" alt="something">
</label>

如果您還需要平滑的頁面滾動動畫,則為了達到輸入元素的頂部偏移,可以改用腳本,例如

Codepen示例: http ://codepen.io/anon/pen/VLyOqg

$(function() {
   $('label[for]').on('click', function(evt) {

      evt.preventDefault();
      var inputId = "#" + $(this).attr('for');

      $('html:not(:animated), body:not(:animated)').animate({
          scrollTop: $(inputId).offset().top
      }, 600, function() {
          $(inputId).focus();
      });
   });
});
<script>
function setFocus(){
    elm = document.getElementById("search");
    jump(elm);
    elm.focus();
}

function jump(elm){
    var top = elm.offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there.
}​
</script>

...

<a href="javascript:setFocus('search')">
<img src="http://www.example.com/images/something.jpg" alt="">
</a>

使用jQuery焦點!

 $('[href="#search"]').click(function(){$('#search').focus();}); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="search" name="search"> <a href="#search"> <img src="http://www.example.com/images/something.jpg" alt=""> </a> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM