【问题标题】:Show div once clicked and hide when clicking outside it单击后显示 div,单击外部时隐藏
【发布时间】:2014-02-13 09:20:25
【问题描述】:

这个问题已被多次询问,但似乎没有一个答案对我有用。 我希望在单击链接时显示 div 然后点击它外面,div隐藏

my code

html:

<a href="#" id='link'>Click here to show div</a>

js:

 $('#link').click(function(e) {
    $('div.termifier').remove();
    $('<div>').addClass('termifier').css({
        position: 'absolute',
        top: event.pageY ,
        left: event.pageX ,
        display: 'none'
        }).appendTo('body')
    .append(
        $('<div>').html("termifier")
     );
     $('div.termifier').fadeIn('slow');
 });

$('html').click(function() {
    $('div.termifier').fadeOut();
 });

 $('div.termifier').click(function(e){
     e.stopPropagation();
 });

css

div.termifier {
  background-color: cornsilk;
  width: 256px;
  color: brown;
  padding: 8px;
  font-size: 0.8em;
}

【问题讨论】:

    标签: jquery click


    【解决方案1】:

    使用e.stopPropagation()

    $('#link').click(function(e) {
        e.stopPropagation();
        /* Rest of the code for clicking */
    });
    

    DEMO

    如果您还想在单击 div 时防止淡入淡出,请执行以下操作:

     $(document.body).bind('click','.termifier',function(e){
         e.stopPropagation();
     });
    

    如果您要使用比 1.6.4 更新的 jQuery 版本,您可以使用 .on() 而不是 .bind()

    DEMO

    【讨论】:

    • 点击链接时,div不显示
    • 你试过我链接的 jsFiddles 了吗?
    • @naser 那是因为 event.pageX 未定义使用 e.pageX 而不是看这个小提琴jsfiddle.net/4yBGt/187
    • @naser 不要这样编辑代码,它不应该以 });其余的代码应该在那个事件中......
    猜你喜欢
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多