当" Up"以及如何使边框上下移动?和" Down"单击按钮?

时间:2017-11-17 15:17:57

标签: jquery

当我点击向上或向下按钮时,我只想让边框上下移动。



$(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>
&#13;
&#13;
&#13;

如何使用jQuery实现这一目标?

2 个答案:

答案 0 :(得分:2)

我就是这样做的(代码注释):

&#13;
&#13;
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')
});
&#13;
.border {
    border:2px solid blue;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以尝试这样的事情:

$(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>