div

时间:2017-09-14 13:27:02

标签: javascript html css

我有一排,里面有X列。如果列溢出,我怎么能替换常规滚动条,每边都有左/右图像箭头。请参阅下面示例中的小于和大于箭头,看看我的意思。

我想保留它的香草JS,而不是jQuery。

div {
  display: inline-block;
  box-sizing: border-box;
  position: relative;
}

.container {
  width: 300px;
  border: 1px solid black;
  position: relative;
  white-space: nowrap;
}

.row {
  width: 90%;
  overflow-x: scroll;
}

.col {
  width: 100px;
  height: 30px;
}

.grey {
  background-color: #cccccc;
}
<div class="container">
  &lt;
  <div class="row">

    <div class="col">
      one
    </div>
    <div class="col grey">
      two
    </div>
    <div class="col">
      three
    </div>
    <div class="col grey">
      four
    </div>
    <div class="col">
      five
    </div>
    <div class="col grey">
      six
    </div>

  </div>
  &gt;
</div>

1 个答案:

答案 0 :(得分:1)

If you don't want to use jQuery, we can add ID's to the lt and gt symbols. This way we can target the images in an onclick event.

HTML:

<div class="container">
  <span id="lt">&lt;</span>
  <div id="row">

    <div class="col">
      one
    </div>
    ...
    <div class="col grey">
      six
    </div>

  </div>
  <span id="gt">&gt;</span>
</div>

Then add onclick handlers to the symbols to scroll through the row.

JS:

var row = document.getElementById("row");
row.scrollRight = 0;
row.scrollLeft = 0;

document.getElementById("lt").onclick = function(){
    row.scrollLeft = row.scrollLeft - 50;
}

document.getElementById("gt").onclick = function(){
    row.scrollLeft = row.scrollLeft + 50;
}

Last, lets remove the horizontal scrollbar.

CSS:

#row {
  width: 90%;
  overflow-x: hidden;
}

Working fiddle here: https://fiddle.jshell.net/26jrtdky/1/