Javascript 滚动到特定的<;img>;或<;a>;当我点击我网站上的搜索按钮时进行标记

Javascript 滚动到特定的<;img>;或<;a>;当我点击我网站上的搜索按钮时进行标记,javascript,jquery,html,image,scroll,Javascript,Jquery,Html,Image,Scroll,正如标题所说,当我在搜索栏上搜索图像时,我希望页面向下滚动到图像 这是搜索栏/按钮的HTML: <form id="search-form" href="#test1" class="smoothscroll"> <input type="text" id="searchText"/> <input type="button" value="Search" id="searchButton"/> </form> 我一直收到以下错误

正如标题所说,当我在搜索栏上搜索图像时,我希望页面向下滚动到图像

这是搜索栏/按钮的HTML:

<form id="search-form" href="#test1" class="smoothscroll">
    <input type="text" id="searchText"/>
    <input type="button" value="Search" id="searchButton"/>
</form>
我一直收到以下错误消息:

未捕获的TypeError:无法读取未定义的属性“top”

感谢您的帮助:)

您的HTML中没有
$('#test1')
。jQuery选择器
#test1
查找id为“test1”的元素。尝试将该
id
添加到您的
a

$(document).ready(function () {
    $( "#searchButton" ).click(function() {
        //var text = document.getElementById('searchText').value;
        $( "html, body" ).animate({     
            scrollTop: ($('#test1').offset().top)
        }, 2000);
    });
});

以确保这些内容。)

请将“id=1”添加到您的任何图像中。

您应该向该锚添加一个id,否则技术上您可以:

<a id="test1" href="test1.html" style="text-decoration: none">

我仍然建议给它一个
id=“test1”

添加
id=“test1”
,或者使用
$([href*='test1']:first”).offset().top
测试是否$(“#test1”)。长度在动画之前大于0()这可能只是修复了症状,而不是根本的问题。

您想要这样的东西

HTML:


下面是。我在
链接中添加了一个大的空白,以查看滚动效果。

消息表明
offset()
返回了
未定义的
,这表示
$(“#test1”)
没有选择任何内容,这表明您没有id为
test1
的元素。事实上,我在您发布的代码片段中没有看到该元素。
\test1
不存在。请将“id=test1”添加到任何输入中。
<a id="test1" href="test1.html" style="text-decoration: none">
$('a[href="test1.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>
$(document).ready(function () {
    $( "#searchButton" ).click(function() {

    var text = $('#searchText').val().toLowerCase();

    $( "html, body" ).animate({     
        scrollTop: ($('#'+text).offset().top)
    }, 2000);
    });
});