jQuery slideToggle方向

13

我正在尝试使用 jQuery 的 .slideToggle 滑动效果,但是我无法在单击 div(导航)时添加从左到右或从右到左的方向。请帮帮我,下面是我的代码。

    <!DOCTYPE html>

<html>

<head>

  <style>

  p { width:400px; float:right;background:#e4e4e4; margin:5px;padding:5px;}

  </style>

  <script src="http://code.jquery.com/jquery-latest.js"></script>

</head>

<body style="font-size:10px; color:#333;">

  <div style="width:50px; height:15px;float:right;background:#ccc;border:1px solid #333;text-align:center;">Nav</div>



  <p>

    This is the paragraph to end all paragraphs.  You

    should feel <em>lucky</em> to have seen such a paragraph in

    your life.  Congratulations!

  </p>

<script>

    $("div").click(function () {

      $("p").slideToggle("slow");


    });

</script>



</body>

我是Jquery的新手,非常需要帮助。


slideToggle 的默认行为是向上或向下滑动。你想让你的 <p> 向左滑动和向右滑动吗? - Amrit
4个回答

10

你需要给这段文本添加一个父元素。

$('.nav').click(function() {
   $('.text p').css({
      'width': $('.text p').width(),
      'height': $('.text p').height()
   });
   $('.text').animate({
      'width': 'toggle'
   });
});
body {
   font-size: 10px;
   color: #333;
}

.nav {
   float: right;
   width: 50px;
   line-height: 38px;
   text-align: center;
   background: #ccc;
   border: 1px solid #333;
   cursor: pointer;
}

.text {
   overflow: hidden;
   float: right;
   margin: 0 5px;
   padding: 5px;
   background: #e4e4e4;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
   <div class="nav">Nav</div>
   <div class="text">
      <p>
         This is the paragraph to end all paragraphs. You
         should feel <em>lucky</em> to have seen such a paragraph in
         your life. Congratulations!
      </p>
   </div>
</body>

您可以在此链接查看演示。


3
在jquery中,slideToggle的默认行为是“向上滑动”或“向下滑动”。如果您希望您的<p>元素“向左滑动”和“向右滑动”,则可以使用jquery ui中提供的“slide”效果。方向参数接受'up','down','left','right'作为有效值。http://docs.jquery.com/UI/Effects/Slide

0
你可以这样做:
p { width:400px; position: absolute; background:#e4e4e4; margin:5px;padding:5px;}

(使用绝对定位而不是右浮动)

还有这个:

 $(document).ready(function() {
    var $elem = $("p");           
    var docwidth =  $(document).width();
    var inileft = docwidth - $elem.outerWidth();
    $elem.css("left", inileft);  //Position element tho the right
    $("div").click(function () {  //This slides
      $elem.animate({
        left: (parseInt($elem.css("left"), 10) >= docwidth ?  inileft : docwidth)
      });
   });
 });

通过使用动画效果,您可以创建非常自定义的动画。希望这能帮到您。谢谢。


非常感谢您的快速回复,但这并没有起作用 :( 请查看下面的链接 http://jsfiddle.net/sanketrajdeora/CJLT3/ - Sanket

-5
<script>

    $("div").click(function () {

      $("p").slideToggle("slow", {direction: "left"}, 100);


    });

</script>

你需要使用jQuery UI才能使其正常工作:https://api.jqueryui.com/slide-effect/?rdfrom=http://docs.jquery.com/mw/index.php - Prid

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接