javascript - ウェブサイトで検索ボタンを押すと
、特定のタグまたはタグまでスクロールする
6 に答える
$('#test1')
あなたのHTMLにはありません。jQuery セレクターは、「test1」#test1
の要素を探します。id
それをあなたに追加してみてid
くださいa
:
<a id="test1" href="test1.html" style="text-decoration: none">
また、タグhref="#test1"
の有効な属性ではないと思います。form
何にも使用されていないので、おそらく必要ありません。(フォームのclass
属性もおそらく不必要であり、技術的に無効である可能性があります。これらのことを確認するために、マークアップを検証する必要があります。)
画像に「id=1」を追加してください。
そのアンカーに ID を追加する必要があります。そうしないと、技術的に次のことができます。
$('a[href="test1.html"]')
私はまだそれに与えることをお勧めしますid="test1'
id="test1"
必要な画像に追加します。または使用$("a[href*='test1']:first").offset().top
animate() 呼び出しの前に $("#test1").length が > 0 かどうかをテストします。ただし、これは根本的な問題ではなく、症状を修正するだけである可能性があります。
あなたはこのようなものが欲しいです。
HTML:
<form id="search-form" href="#test1" class="smoothscroll">
<input type="text" id="searchText"/>
<input type="button" value="Search" id="searchButton"/>
</form>
<a style="margin-top: 1000px; display: inline-block;" href="test1.html" style="text-decoration: none">
<img src="pic1.png" id="image1" />
<img src="pic2.png" id="image2"/>
</a>
JS:
$(document).ready(function () {
$( "#searchButton" ).click(function() {
var text = $('#searchText').val().toLowerCase();
$( "html, body" ).animate({
scrollTop: ($('#'+text).offset().top)
}, 2000);
});
});
ここにJsFiddleがあります。<a>
スクロール効果を確認するために、リンクに大きな余白を追加しました。