【发布时间】:2018-10-04 00:45:48
【问题描述】:
我的页面底部有一个“向上箭头”的小图标图像。
如何使这个图像成为一个可点击的按钮并跳转到页面顶部?
我是 HTML 新手,这是我的第一个项目,所以请多多包涵。
到目前为止我已经尝试过:
input type="button" id="btnx" style="background-image:url('arrowup.png')"
【问题讨论】:
我的页面底部有一个“向上箭头”的小图标图像。
如何使这个图像成为一个可点击的按钮并跳转到页面顶部?
我是 HTML 新手,这是我的第一个项目,所以请多多包涵。
到目前为止我已经尝试过:
input type="button" id="btnx" style="background-image:url('arrowup.png')"
【问题讨论】:
试试这个:将你的图片包裹在一个锚(A标签)链接“#”将转到顶部
<a href="#"><img src="/some-image-folder/arrowup.png"></a>
也许你的html是这样的:
<a href="#"><i class="fa fa-arrow-up" aria-hidden="true"></i></a>
也许您想使用输入按钮?好的:
<form>
<input type="button" value="Click me" onclick="$(window).scrollTop(0);">
</form>
【讨论】:
如果你不想直接跳到顶部,这里有一个动画方法。
带有图像的动画:
function topFunction() {
if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) {
window.scrollBy(0, -50);
requestAnimationFrame(topFunction);
}
}
.test {
background-color: lightgrey;
padding: 30px;
height: 2500px;
margin-bottom: 10px;
}
<div class="test">Scroll to Bottom</div>
<a href="javascript:void(0)" onclick="topFunction();" id="btnx"><img alt="Click" src="/images/arrowup.png"></a>
符号动画:
function topFunction() {
if (document.body.scrollTop !== 0 || document.documentElement.scrollTop !== 0) {
window.scrollBy(0, -50);
requestAnimationFrame(topFunction);
}
}
.test {
background: lightgrey;
padding: 30px;
height: 2500px;
margin-bottom: 10px;
}
.uparrow {
color: white;
background: black;
font-size: 22px;
padding: 5px;
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<div class="test">Scroll to Bottom</div>
<a href="javascript:void(0)" onclick="topFunction();" id="btnx"><i class="material-icons uparrow"></i></a>
【讨论】:
查看FIDDLE
HTML
<h1>Top of the page</h1>
<article style="height: 1000px">
<p style="margin-bottom: 600px">Scroll down the page…</p>
<p>Then click the box.</p>
<a href="#" class="scrollup">Scroll</a>
</article>
脚本
$(document).ready(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('.scrollup').fadeIn();
} else {
$('.scrollup').fadeOut();
}
});
$('.scrollup').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
【讨论】: