使用两个带有 onclick 事件的按钮,并且不断地互相改变?

问题描述 投票:0回答:1

这就是我想要实现的目标:

两个按钮(左和右)。左侧按钮开始时悬停时光标为“不允许”(表示不应单击左侧按钮)。当单击右侧按钮时,这会将右侧按钮的光标悬停时变为“不允许”,表示单击一次后不应单击该按钮,同时使左侧按钮的光标悬停时变为“箭头”,表示左侧按钮是现在点击右键后打开即可点击。

我使用 javascript 和“onclick 事件”编写了一些代码。这段代码不是我想要的,但可以让您直观地了解我正在尝试完成的任务,正如我上面所解释的:

function prev() {
  document.getElementById("slide-arrow-prev").style.cursor = "not-allowed";
  document.getElementById("slide-arrow-next").style.cursor = "arrow";
}

function next() {
  document.getElementById("slide-arrow-next").style.cursor = "now-allowed";
}
<body>
  <button id="slide-arrow-prev" onclick="prev()"> < </button>
  <button id="slide-arrow-next" onclick="next()"> > </button>
</body>

基本上,这个想法是一个图像轮播,当按下左右按钮时会滑动。我正在尝试模仿速卖通主页上使用的轮播(您可以在那里查找参考)。一旦轮播达到滑动极限,左/右按钮的光标将“不允许”,表示它们无法再滑动图像。

我尝试使用事件监听器,但不太确定是否应该这样做,所以我把它去掉了。

如何使用 html、javascript 和/或 CSS 编写此内容?

javascript html button onclick event-listener
1个回答
0
投票

您可以打开和关闭

.not-allowed
类,以便更改每个按钮的光标。

function handleClick(e) {

  ['slide-arrow-prev', 'slide-arrow-next'].forEach(id => 
    document.getElementById(id).classList.toggle('not-allowed'))

  console.log(`${e.currentTarget.id} clicked`)

}
button {
  cursor: arrow;
}

.not-allowed {
  cursor: not-allowed;
}
<button id="slide-arrow-prev" onclick="handleClick(event)" class="not-allowed"> &lt; </button>
<button id="slide-arrow-next" onclick="handleClick(event)"> &gt; </button>

© www.soinside.com 2019 - 2024. All rights reserved.