如何使用纯JS制作弹出脚本? [英] How to make a popup script with pure JS?

查看:94
本文介绍了如何使用纯JS制作弹出脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用纯JS编写一个脚本,以便在加载页面时显示弹出窗口.
背景需要褪色,我必须将自己的内容添加到弹出窗口中. 我不想使用CSS或HTML.
将CSS和HTML放入Javascript代码中. 有人可以帮我吗?
我可以自己做造型.
我只能使用外部CSS和HTML弹出窗口,而不能使用纯JS弹出窗口. 它只能是用纯JS编写的简单弹出窗口,它会在页面加载时弹出.

I need to make a script in pure JS for showing an popup when the page is loaded.
The background needs to be faded and i have to add my own content into the popup. I don't want to use CSS or HTML.
Put the CSS and HTML into the Javascript code. Can someone help me with this?
I can do styling on my own.
I can only make an popup with external CSS and HTML, not pure JS. It only must be a simple popup written in pure JS en it pops up when the page is loaded.

请帮助我!

Please help me!!

我更喜欢使用JSFiddle.

I prefer the use of JSFiddle.

推荐答案

更新后的答案:

您可以简单地使用css的display样式属性,以及使用css在按钮隐藏/显示popup样式的onClick上.

You can simply use display style property of css and on onClick of button hide/show popup style using css.

  • 在DOM中添加弹出式占位符

  • add popup placeholder element in DOM

添加css进行弹出-请参见答案中提供的css

add css for popup - see css provided in answer

使用 innerHTML JS的属性,以及用于显示/隐藏弹出窗口的必需JS

add pop DOM using innerHTML property of JS and required JS for show/hide popup

类似以下内容-

document.body.onload = addElement;

function addElement () { 
  // create a new div element 
  // and give it popup content 
  var newDiv = document.createElement("div"); 
  newDiv.innerHTML +='<button class="open_button" onClick="openPopup()">Open Popup</button><div id="popup" style="  position: absolute;width: 300px;z-index: 999;display: none;top:0;background-color: #fff;  border: 1px solid #ddd;  border-radius: 5px;  box-shadow: 0 2px 8px #aaa;  overflow: hidden;   padding: 10px;"><div class="popup_body" style="  height: 100px;">This is sample popuup</div><button class="close_button"onClick="closePopup()">close</button</div>';   

  // add the newly created element and its content into the DOM 
  var currentDiv = document.getElementById("main_container"); 
  document.body.insertBefore(newDiv, currentDiv); 

  // open popup onload
  openPopup();
}

function openPopup() {
  var el = document.getElementById('popup');
  el.style.display = 'block';
  
  // Updates: set window background color black
  document.body.style.background = '#353333';
}

function closePopup() {
  var el = document.getElementById('popup');
  el.style.display = 'none';
  document.body.style.background = 'white';
}

希望这会对您有所帮助(y).

Hope this will help you in some way (y).

这篇关于如何使用纯JS制作弹出脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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