HTML DOM scrollLeft 属性
htmlweb developmentfront end technology更新于 2025/6/6 7:08:17
DOM scrollLeft 属性返回并修改元素内容在 HTML 文档中水平滚动的值(以像素为单位)。
语法
以下是语法 −
返回 scrollLeft
element.scrollLeft
添加 scrollLeft
element.scrollLeft = value
此处 value 以像素为单位
示例
让我们看一个 scrollLeft 属性的示例 −
<!DOCTYPE html>
<html>
<head>
<style>
body{
text-align:center;
color:#fff;
background: #ff7f5094;
height:100%;
}
p{
font-weight:700;
font-size:1.8rem;
height:80px;
overflow:auto;
width:150px;
margin:20px auto;
}
.btn{
background:#0197F6;
border:none;
height:2rem;
border-radius:2px;
width:35%;
margin:2rem auto;
display:block;
color:#fff;
outline:none;
cursor:pointer;
}
.show{
font-size:1.5rem;
}
#myDIV {
height: 200px;
width: 200px;
overflow: auto;
margin:20px auto;
}
#content {
height: 400px;
width: 1000px;
background-color: lightblue;
}
</style>
</head>
<body>
<h1>DOM scrollLeft/scrollTop Property Demo</h1>
<div id="myDIV" onscroll="display()">
<div id="content"></div>
</div>
<div class="show"></div>
<script>
function display() {
var elmnt = document.getElementById("myDIV");
var x = elmnt.scrollLeft;
var y = elmnt.scrollTop;
document.querySelector(".show").innerHTML = "Top Scroll = " + x + "px Left Scroll = " + y + "px";
}
</script>
</body>
</html>
输出
这将产生以下输出 −

现在在蓝色框内滚动以获取顶部滚动和左侧滚动的值。

相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

