jQuery:div直到第二次点击才出现?我首先要. = \ [英] jQuery: div doesn't appear until second click? I want it on the first. =\

查看:86
本文介绍了jQuery:div直到第二次点击才出现?我首先要. = \的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首次点击:清空floatymessage div.第二次点击并在之后:有效.

First click: empty floatymessage div. second click and after: works.

jQuery:

function floatymessage(message){
    var box = $j(".floatymessage")
    if (box.length == 0) {
        $j('body').append("<div class='floatymessage'></div>");
    }
    box.html(message);
    // center it
    box.css("left", ( $j(window).width() - box.width() ) / 2+$j(window).scrollLeft() + "px");
    box.fadeIn('slow');

    setTimeout(function(){$j('.floatymessage').fadeOut('slow');},3500);
}

链接:

<a href="#" onclick="floatymessage('Asking questions is not allowed.');"></a>

floarymessoge的CSS:

css for floatymessoge:

div.floatymessage {
    position: absolute;
    top: 20%;
    width: 300px;
    height: 50px;
    background: black;
    color: white;
    text-align: center;
    filter:alpha(opacity=75);
    -moz-opacity:0.75;
    -khtml-opacity: 0.75;
    opacity: 0.75;
    box-shadow: 10px 10px 5px #000;
    border: 1px solid black;
    border-bottom-left-radius: 5px 5px;
    border-bottom-right-radius: 5px 5px;
    border-top-left-radius: 5px 5px;
    border-top-right-radius: 5px 5px;
    line-height: 50px;
    z-index: 10000;
    display: none;
}

推荐答案

您带框的逻辑缺少一个步骤,如果dom中尚未包含该步骤,则需要将变量"box"设置为新的div:

Your logic with box was missing a step, if it is not already in the dom you need to set your variable 'box' to the new div:

if (box.length == 0) {
  box = $j("<div class='floatymessage'></div>");
  $j('body').append(box);
}

进一步

您可以使用已设置的方法,但是在使用锚标记触发javascript事件时,您需要添加return false来阻止其像正常链接一样处理它.

You can use the method you have setup but when using an anchor tag to fire a javascript event you need to add a return false to stop it from processing it like a normal link.

<a id="mine" href="#" onclick="floatymessage('msg');return false;">run</a>

在这种情况下,最好绑定事件:

It is a better practice to bind events in this case:

$j("#mine").click(function() { floatymessage('msg'); });

使用span标签而不是要导航到url的锚标签,可以达到相同的效果.

You could achieve the same effect using a span tag instead of an anchor tag that wants to navigate to a url.

<span id="mine" onclick="floatymessage('msg');">run</span>

这篇关于jQuery:div直到第二次点击才出现?我首先要. = \的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆