jQuery问题与onclick上滑功能

时间:2016-09-09 10:34:21

标签: javascript jquery

我在jquery中有滑动和滑动功能的脚本,每个都有一个按钮。  两者都工作正常,直到我想通过让用户点击网站中的任何位置来放弃幻灯片。即,当用户点击向下滑动按钮时,它向下滑动,当他点击屏幕上的任何地方时,内容会向上滑动。 / p>

不幸的是,当我点击向下滑动按钮时,它有一个小问题,即自动滑落并向上滑动。

脚本如下::

<div id="a" name="a">
    </br>
    <small><p id="date2"><?php echo $row2["date"]; ?></p></small>
    <p><B><big><font color= #ba4a00> A:</font></B></big> <small><?php echo $row2["answer"]; ?></small></p>
</div>

<button id="showmoreless" class="hide">Hide Answers</button>
        <button id="showmoreless" class="show">Show Answers</button>

<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>

<script>
    $(document).ready(function(){
        $(".hide").hide();
        $('[name="a"]').slideUp();
        $(".show").click(function(e){
            e.preventDefault();
            $(this).parent().find('[name="a"]').slideDown();
            $(this).hide();
            $(this).parent().find(".hide").show();
        }); 

        $('[name="a"]').click(function(e){
            e.stopPropagation();
        });

        $(window).click(function(e) {
            console.log($(e.target));
            if (!$(e.target).is('[name="a"]')) {
                $('.show').show();
                $('[name="a"]').slideUp(); 
            }
        });

    });
</script>

任何帮助都是赞赏的。

1 个答案:

答案 0 :(得分:0)

它会立即向上滑动,因为您的事件处理程序都在执行 - 根据定义,单击show元素也是单击窗口。

要阻止这种情况发生,您需要stopPropagation

&#13;
&#13;
$(".hide").hide();
$('[name="a"]').slideUp();
$(".show").click(function(e){
  e.preventDefault();
  $(this).parent().find('[name="a"]').slideDown();
  $(this).hide();
  $(this).parent().find(".hide").show();
  e.stopPropagation(); // <-- here
}); 

$('[name="a"]').click(function(e){
  e.stopPropagation();
});

$(window).click(function(e) {
  //console.log($(e.target));
  if (!$(e.target).is('[name="a"]')) {
    $('.show').show();
    $('[name="a"]').slideUp(); 
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="a" name="a">
    <br>
    <small><p id="date2">date here</p></small>
    <p><big><font color= #ba4a00> A:</font></big> <small>answer here</small></p>
</div>

<button id="showmoreless" class="hide">Hide Answers</button>
<button id="showmoreless" class="show">Show Answers</button>
&#13;
&#13;
&#13;

相关问题