Búsqueda de sitios web

javascript - desplazar la parte visible de un div desbordado dentro de un div más pequeño sin jquery


Actualmente estoy tratando de mover horizontalmente un div B más ancho dentro de un <div> A más pequeño usando dos botones.
Encontré un problema similar usando jQuery, pero no quiero usar la biblioteca solo para esta sección del código.

Aquí está el violín

Quiero desplaz ar el campo de visión visible usando un botón de 'izquierda' y 'derecha' para mover el campo 100px en cualquier dirección sin usar jquery, pero con Javascript, HTML y CSS puro.

<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>

Respuesta #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>

Respuesta #2

Bueno, eso es muy fácil si modificas la propiedad scrollLeft que se puede escribir:

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>