javascript - 在不使用 jquery 的情況下,滾動小 div 內溢出的 div 的可見部分
我目前正在嘗試使用兩個按鈕將一個較寬的 div B 水平移動到一個較小的 <div> A 內。
我找到了一個使用 jQuery 的類似問題,但我不想僅為了這段程式碼使用這個庫。
這裡是小提琴
我想使用「左」和「右」按鈕滾動可見的視野,讓視野向任一方向移動100像素,且不使用 jQuery,而是純粹用 Javascript、HTML 和 CSS。
<div id="outer-div" style="width:250px;overflow:hidden;">
<div style="width:750px;">
<div style="background-color:orange;width:250px;height:100px;float:left;">
</div>
<div style="background-color:red;width:250px;height:100px;float:left;">
</div>
<div style="background-color:blue;width:250px;height:100px;float:left;">
</div>
</div>
</div>
<button>left</button>
<button>right</button>答案#1
var outerDiv = document.getElementById('outer-div');
function moveLeft() {
outerDiv.scrollLeft -= 100;
}
function moveRight() {
outerDiv.scrollLeft += 100;
}
var leftButton = document.getElementById('left-button');
var rightButton = document.getElementById('right-button');
leftButton.addEventListener('click', moveLeft, false);
rightButton.addEventListener('click', moveRight, false);<div id="outer-div" style="width:250px;overflow:hidden;">
<div style="width:750px;">
<div style="background-color:orange;width:250px;height:100px;float:left;">
</div>
<div style="background-color:red;width:250px;height:100px;float:left;">
</div>
<div style="background-color:blue;width:250px;height:100px;float:left;">
</div>
</div>
</div>
<button id="left-button">left</button>
<button id="right-button">right</button>答案#2
嗯,如果你修改可寫的 scrollLeft 屬性,那就非常簡單:
document.getElementById('to-right').onclick = function() {
document.getElementById('outer-div').scrollLeft += 100;
}
document.getElementById('to-left').onclick = function() {
document.getElementById('outer-div').scrollLeft -= 100;
}<div id="outer-div" style="width:250px;overflow:hidden;">
<div style="width:750px;">
<div style="background-color:orange;width:250px;height:100px;float:left;"></div>
<div style="background-color:red;width:250px;height:100px;float:left;"></div>
<div style="background-color:blue;width:250px;height:100px;float:left;"></div>
</div>
</div>
<button id="to-left">left</button>
<button id="to-right">right</button>