为什么滚动代码不起作用?我希望在单击 $('#openDiv')
时滚动到底部。
示例:当您在 stackoverflow 上进入聊天室时,您会看到默认情况下滚动条位于底部,我想要这个。
我也试过把滚动代码放在点击函数外面,但是不行...
$(document).ready(function() {
$('#openDiv').on('click', function(){
$('#openDiv').hide();
$('#closeDiv').show();
///////// NOT WORKING /////////
$("#mainDiv").animate({
scrollTop: $('#mainDiv').prop("scrollHeight")
}, 1000);
///////// NOT WORKING /////////
$("#mainDiv").show();
});
$('#closeDiv').on('click', function(){
$('#closeDiv').hide();
$("#mainDiv").hide();
$('#openDiv').show();
});
});
#mainDiv {
height: 150px;
background-color: #2A2A2A;
overflow-y: auto;
overflow-x: hidden;
display: none;
}
#divText {
color: #fff;
background-color: #555555;
height: 20px;
}
#divTextEnd{
color: #fff;
background-color: red;
height: 20px;
}
#openDiv{
background-color: green;
border: none;
color: #fff;
}
#closeDiv{
display: none;
background-color: red;
border: none;
color: #fff;
}
<button id="openDiv">Open div</button>
<button id="closeDiv">Close div</button>
<div id="mainDiv">
<div id="divText">
<h5>text</h5>
</div>
<div id="divText">
<h5>text</h5>
</div>
<div id="divText">
<h5>text</h5>
</div>
<div id="divText">
<h5>text</h5>
</div>
<div id="divTextEnd">
<h5>text</h5>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
在你调用 $('#mainDiv').prop("scrollHeight")
的那一刻,#mainDiv
被隐藏了 display: none;
。这样的元素的 scrollHeight
为 0。
在尝试滚动之前显示 #mainDiv
:
$(document).ready(function() {
$('#openDiv').on('click', function() {
$('#openDiv').hide();
$('#closeDiv').show();
$("#mainDiv").show();
$("#mainDiv").animate({
scrollTop: $('#mainDiv').prop("scrollHeight")
}, 1000);
});
$('#closeDiv').on('click', function() {
$('#closeDiv').hide();
$("#mainDiv").hide();
$('#openDiv').show();
});
});
#mainDiv {
height: 150px;
background-color: #2A2A2A;
overflow-y: auto;
overflow-x: hidden;
display: none;
}
#divText {
color: #fff;
background-color: #555555;
height: 20px;
}
#divTextEnd {
color: #fff;
background-color: red;
height: 20px;
}
#openDiv {
background-color: green;
border: none;
color: #fff;
}
#closeDiv {
display: none;
background-color: red;
border: none;
color: #fff;
}
<button id="openDiv">Open div</button>
<button id="closeDiv">Close div</button>
<div id="mainDiv">
<div id="divText">
<h5>text</h5>
</div>
<div id="divText">
<h5>text</h5>
</div>
<div id="divText">
<h5>text</h5>
</div>
<div id="divText">
<h5>text</h5>
</div>
<div id="divTextEnd">
<h5>text</h5>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
我是一名优秀的程序员,十分优秀!