首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用onclick上滑功能时的JQuery问题

问使用onclick上滑功能时的JQuery问题
EN

Stack Overflow用户
提问于 2016-09-09 18:34:21
回答 1查看 235关注 0票数 0

我在jquery中有用于向上滑动和向下滑动功能的脚本,并且每个都有一个按钮。两者都工作得很好,直到我想要放弃幻灯片,让用户点击站点中的任何地方。即,当用户点击向下滑动按钮时,其向下滑动,而当他稍后点击屏幕上的任何地方时,内容向上滑动。

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

脚本如下:

代码语言:javascript
复制
<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>

任何帮助都将不胜感激..

EN

回答 1

Stack Overflow用户

发布于 2016-09-09 18:44:51

它会立即返回,因为两个事件处理程序都在执行-根据定义,在show元素上单击也是在窗口上单击。

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

​

代码语言:javascript
复制
$(".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(); 
  }
});
代码语言:javascript
复制
<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>

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39409579

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档