首页 > 解决方案 > JS 在特定 div 中定位图像,即使它们共享类

问题描述

我目前有一个 PHP 循环提供的图像,我使用 JS 来制作轮播。这为我提供了一个幻灯片样式的图像选择,我可以将其拖入编辑器并应用于页面:

<div class="w3-content w3-display-container">
      <?php foreach ($imageResult as $im): ?>
        <?php if($im['type'] == 'content'){?>

          <img class="mySlides" src="<?php echo $im['url']; ?>" style="max-width:200px; max-height:200px;">

        <?php } ?>
      <?php endforeach?>
    <button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
    <button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button>
</div>

<script>
var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";  
  }
  x[slideIndex-1].style.display = "block";  
}
</script>

这可行,但有一个问题:

选择图像并将其拖入页面区域后,例如:

<div class="fullContent"  id="fullContent" style="background-color:white; border: dotted 1px black;">
        <!--Image would be here-->
</div>

它仍然具有类,mySlides所以当我使用箭头在选择器中的图像之间移动时,它也会移动保存到页面上 div 中的图像。

有没有办法改变 JS,使箭头只移动实际 w3-content div 中包含的图像?

标签: javascriptphphtmlcssstring

解决方案


针对您关于一次显示多个项目的后续问题(仅因为我还没有评论权限而发布为新答案):

这应该可以解决问题。

主要区别在于对超出范围索引的任何测试都发生在一个单独的函数中,该函数在循环中调用以处理几个不同的索引——它动态设置新值(而不是总是将它们设置为“x.长度”或“1”。)

我还为项目列表使用了一个从零开始的数组(或者,从技术上讲,“类数组对象”)并重命名了几个变量,但这只是个人喜好问题。

(编辑:请注意,新显示的图像不会自动位于列表的末尾,因为 HTML 设置了它们的顺序,而脚本只是更改了它们的 style.display 属性。)

const availableSlides = document.querySelectorAll(".w3-content .mySlides");//Renamed
let slideIndex = 0; // Using 0 instead of 1 (for consistency w/ JS arrays)
showDivs();

function plusDivs(delta) { // Almost identical to your original function
  slideIndex += delta;
  showDivs();  
}

function wrap(tentative, max) { //This is where the magic happens
  let actualIndex;
  // If tentative index is too high/low, resumes counting from the bottom/top
  if (tentative > max) { actualIndex = tentative - (max + 1); }
  else if (tentative < 0) { actualIndex = tentative + (max + 1); }
  else { actualIndex = tentative; }
  return actualIndex;
}

function showDivs() { // Takes no args (acts on global slideIndex instead)
  // Hides all slides
  for (let i = 0; i < availableSlides.length; i++) {
    availableSlides[i].style.display = "none";
  }
  // Shows thatMany slides, starting from slideIndex
  const thatMany = 5; // Sets the number of slides to display
  // Calls wrap to keep slideIndex from being out of range
  slideIndex = wrap(slideIndex, availableSlides.length - 1);
  // Calls wrap on thatMany indexes and displays the resulting slides
  for (let j = 0; j < thatMany; j++) {
    let tentativeIndex = slideIndex + j;
    let maxIndex = availableSlides.length - 1;
    availableSlides[wrap(tentativeIndex, maxIndex)].style.display = "block";
  }
}

推荐阅读