javascript onclick create(element)div viz弹出框 [英] javascript onclick create(element) div viz popup box

查看:168
本文介绍了javascript onclick create(element)div viz弹出框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个弹出框,在点击按钮时被调用,这是我到目前为止。 http://jsfiddle.net/WGPhG/2/

I'm trying to make a pop up box, which gets invoked on clicking a button, this is what I've got so far.. http://jsfiddle.net/WGPhG/2/

推荐答案

这里是一个真正做你想要的小提琴 - http://jsfiddle.net/WGPhG/6/

Here is a fiddle that actually does what you want - http://jsfiddle.net/WGPhG/6/

JS

function popUp(){
    var popup = document.createElement('div');
    popup.className = 'popup';
    popup.id = 'test';
    var cancel = document.createElement('div');
    cancel.className = 'cancel';
    cancel.innerHTML = 'close';
    cancel.onclick = function (e) { popup.parentNode.removeChild(popup) };
    var message = document.createElement('span');
    message.innerHTML = "This is a test message";
    popup.appendChild(message);                                    
    popup.appendChild(cancel);
    document.body.appendChild(popup);
}

注意

要在元素上设置类,请使用element.className而不是element.class。
对于cancel元素上的onclick事件处理程序,最好直接指定onclick处理程序与一个匿名函数,这个函数可以像上面的例子那样执行你所需要的。

To set the class on an element you use element.className instead of element.class. For the onclick event handler on the cancel element, it is better to directly assign the onclick handler with an anonymous function that does what you need as in my example above.

编辑(更高效的方式)

您想要的结果,因为每次弹出显示时都不需要重新创建元素。小提琴 - http://jsfiddle.net/WGPhG/7/

This is actually a much better of getting the results that you want because there is no overhead involved with recreating the elements every time the popup is shown. Fiddle - http://jsfiddle.net/WGPhG/7/

CSS

.popup
{
    position:absolute;
    top:0px;
    left:0px;
    margin:100px auto;
    width:200px;
    height:150px;
    font-family:verdana;
    font-size:13px;
    padding:10px;
    background-color:rgb(240,240,240);
    border:2px solid grey;
    z-index:100000000000000000;
    display:none
}

.cancel
{
    display:relative;
    cursor:pointer;
    margin:0;
    float:right;
    height:10px;
    width:14px;
    padding:0 0 5px 0;
    background-color:red;
    text-align:center;
    font-weight:bold;
    font-size:11px;
    color:white;
    border-radius:3px;
    z-index:100000000000000000;
}

HTML

<button onClick="openPopup();">click here</button>
<div id="test" class="popup">
    This is a test message
    <div class="cancel" onclick="closePopup();"></div>
</div>

JS

function openPopup() {
    document.getElementById('test').style.display = 'block';
}

function closePopup() {
    document.getElementById('test').style.display = 'none';
}

这篇关于javascript onclick create(element)div viz弹出框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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