单击"Up"和"Down"按钮时,如何使边框上下移动?



我只想在单击向上或向下按钮时上下移动边框。

$(document).ready(function() {
  $("#up").click(function() {
    $("#up").prev().css("border", "2px solid blue");
  });
});
$(document).ready(function() {
  $("#down").click(function() {
    $("p").next().css("border", "2px solid blue");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four">paragraph 4</p>
<button id="up">Up</button>
<button id="down">Down</button>

如何使用jQuery实现这一点?

这就是我的做法(代码中的注释(:

var ps = $('p'),      // cache the paragraphs
    currentIndex = 3; // starting at paragraph 4
$("#up").click(function() {
  currentIndex -= 1;             // decrement index
  if (currentIndex < 0) {
    currentIndex = ps.length - 1;  // set back to bottom item
  }
  
  ps.removeClass('border');
  ps.eq(currentIndex).addClass('border')
});
$("#down").click(function() {
  currentIndex += 1;              // increment index
  if (currentIndex == ps.length) {
    currentIndex = 0;             // set back to top item
  }
  
  ps.removeClass('border');
  ps.eq(currentIndex).addClass('border')
});
.border {
    border:2px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four" class="border">paragraph 4</p>
<button id="up">Up</button>
<button id="down">Down</button>

你可以尝试这样的事情:

$(document).ready(function() {
  $("#up").click(function() {
    if ($("p.with-border").prev("p").length > 0) { // is there prev paragraph?
      $("p.with-border").prev("p").addClass("with-border");
      $("p.with-border").last().removeClass("with-border");
    }
  });
  $("#down").click(function() {
    if ($("p.with-border").next("p").length > 0) { // is there next paragraph?
      $("p.with-border").next("p").addClass("with-border");
      $("p.with-border").first().removeClass("with-border");
    }
  });
});
.with-border {
  border: 2px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="one">paragraph 1</p>
<p id="two">paragraph 2</p>
<p id="three">paragraph 3</p>
<p id="four" class="with-border">paragraph 4</p>
<button id="up">Up</button>
<button id="down">Down</button>

最新更新