侧面板到顶部。还有其他解决方案吗?

时间:2019-02-19 12:23:10

标签: javascript html css

我试图使按钮在侧面板顶部。但是我遇到了一个问题,因为我需要SIDE面板在滚动时起作用,而不是整个身体。有示例代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="side">
<button onclick="topFunction()" id="topBtn" title="Go to top">Top</button>

<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>

</div>
</body>
<script type="text/javascript" src="js.js"></script>
</html>

JS:

const side = document.getElementById('side');
const top = side.offsetTop;

if (top > 10){
    document.getElementById('topBtn').style.display = "block";
} else {
  document.getElementById('topBtn').style.display = "none";
}

2 个答案:

答案 0 :(得分:1)

function topFunction() {
	  document.body.scrollTop = 0;
	  document.documentElement.scrollTop = 0;
	}
#topBtn{
  position:fixed;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="side">
<button onclick="topFunction()" id="topBtn" title="Go to top">Top</button>

<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>

</div>
<script src="js.js"></script>
</body>
</html>

答案 1 :(得分:0)

尝试一下:

<body>
    <div id="side" style="overflow-y:scroll">
        <div id="top">...</div>
        <div>...</div>
        <div>...</div>
        <div>...</div>

        <div>...</div>
        <div>...</div>
        <div>...</div>
        <div>...</div>

        <div>...</div>
        <div>...</div>
        <div>...</div>
        <div style="background-color:black;color:white;padding:30px">Scroll Down</div>

        <div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>

        <button onclick="topFunction()" id="topBtn" title="Go to top">Top</button>
    </div>
</body>

// your jquery cdn script 
<script>

$(function() {
  $('#topBtn').animate({
    // Scroll to top of body
    scrollTop: 0
  }, 500);
})();

</script>