2015-06-30 17 views
0

我想創建一個輸入鏈接。我當前的鏈接示例工作正常(將我帶到設置id的區域),但我真正想要的是當用戶點擊鏈接以準確輸入輸入內容時,可以立即輸入。點擊一個鏈接並轉到輸入

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

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

這是甚至可以實現沒有JQuery/JavaScript的?請以您能想象的任何方法發佈解決方案。一直在尋找這一點,並找不到答案。

回答

13

無需使用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(); 
     }); 
    }); 
}); 
2
<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> 
1

使用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>

相關問題