jquery 如何通过css或JavaScript为div添加平滑滚动效果?

yqlxgs2m  于 2023-08-04  发布在  jQuery
关注(0)|答案(2)|浏览(109)

创建一个可滚动的div,在点击事件时可以左右滚动。我想用CSS过渡或任何其他方式使滚动效果平滑,请帮助

<div class="cardsliderblock">
<div class="sliderBlock" id="Slidercontent">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
</div>
<span class="btns horizon-prev" id="left-button"><</span>
<span class="btns horizon-next" id="right-button" >></span>
</div>

//JS
const rightBtn = document.querySelector('#right-button');
const leftBtn = document.querySelector('#left-button');

rightBtn.addEventListener("click", function(event) {
  const conent = document.querySelector('#Slidercontent');
  conent.scrollLeft += 150;
  event.preventDefault();
});

leftBtn.addEventListener("click", function(event) {
  const conent = document.querySelector('#Slidercontent');
  conent.scrollLeft -= 150;
  event.preventDefault();
});

// CSS
.sliderBlock {
  display: flex;
  height: 200px;
  border: solid 1px red;
  width: 800px;
  overflow: hidden;
  overflow-x: auto;

  transition: 2s all ease;
}

.sliderBlock>div {
  width: calc(100% / 5.5);
  margin-right: 2.2%;
  border: solid 1px black;
  min-width: 143px;
}

.sliderBlock>div:nth-child(5n) {}

.btns {
  display: inline-block;
  width: 20px;
  height: 20px;
  background: red;
}

字符串
https://jsfiddle.net/anoopsuda/g0fk52ry/31/

djp7away

djp7away1#

对于平滑滚动,您需要使用Element.scrollTo()方法而不是scrollLeft属性。使用scrollTo,您可以传递behavior选项,将其设置为smooth
了解有关Element.scrollTo()的更多信息

Demo:

const rightBtn = document.querySelector('#right-button');
const leftBtn = document.querySelector('#left-button');

rightBtn.addEventListener("click", function(event) {
  const conent = document.querySelector('#Slidercontent');
  // Change 1
  conent.scrollTo({
    top: 0,
    left: conent.scrollLeft + 150,
    behavior: "smooth",
  });

  event.preventDefault();
});

leftBtn.addEventListener("click", function(event) {
  const conent = document.querySelector('#Slidercontent');
  // Change 2
  conent.scrollTo({
    top: 0,
    left: conent.scrollLeft - 150,
    behavior: "smooth",
  });

  event.preventDefault();
});
.sliderBlock {
  display: flex;
  height: 200px;
  border: solid 1px red;
  width: 800px;
  overflow: hidden;
  overflow-x: auto;
  transition: 2s all ease;
}

.sliderBlock>div {
  width: calc(100% / 5.5);
  margin-right: 2.2%;
  border: solid 1px black;
  min-width: 143px;
}

.sliderBlock>div:nth-child(5n) {}

.btns {
  display: inline-block;
  width: 20px;
  height: 20px;
  background: red;
}
<div class="cardsliderblock">
  <div class="sliderBlock" id="Slidercontent">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
  </div>
  <span class="btns horizon-prev" id="left-button"><</span>
  <span class="btns horizon-next" id="right-button">></span>
</div>
csga3l58

csga3l582#

您可以使用

*{
    scroll-behavior: smooth;
}

字符串
使其平滑

相关问题