JavaScript實現(xiàn)alert彈框效果
本文實例為大家分享了JavaScript實現(xiàn)alert彈框的具體代碼,供大家參考,具體內(nèi)容如下
因本人水平有限,不足之處還望大家指正。先上圖:

為什么會出現(xiàn)這個需求?瀏覽器自帶的alert不好用嗎?
自帶的alert在不同的瀏覽器是有差異的,而且樣式也不美觀,用戶體驗度不是很好。所以我們要自己寫一個alert彈框,這樣我們就可以按照我們自己的需求,把alert彈框做的美觀一點。
以下是alert.js代碼:
var myAlert = { alertbox : function(alertContent){ var windowWidth = window.innerWidth; windowHeight = window.innerHeight; alertContainer = document.createElement('div'); alertContainer.id = 'myAlertBox'; alertContainer.style.cssText='position:absolute;left:0px;top:0px;width:100%;z-index:9999;'; alertContainer.style.height = windowHeight+'px'; alertOpacity = document.createElement('div'); alertOpacity.style.cssText='position:absolute;left:0px;top:0px;width:100%;background:#000;opacity:0.5;z-index:9999;'; alertOpacity.style.height = windowHeight+'px'; alertContainer.appendChild(alertOpacity) alertMainBox = document.createElement('div'); alertMainBox.style.cssText='position:absolute;width:200px;height:200px;line-height:200px;text-align:center;background:green;z-index:10000;' alertMainBoxLeft = (windowWidth-200)/2; alertMainBoxTop = (windowHeight-200)/2; alertMainBox.style.left = alertMainBoxLeft+'px'; alertMainBox.style.top = alertMainBoxTop+'px'; alertMainBox.innerHTML = alertContent; alertContainer.appendChild(alertMainBox); alertClose = document.createElement('div'); alertClose.id = 'closeBox'; alertClose.style.cssText = 'position:absolute;right:0px;top:0px;width:30px;height:30px;background:red;cursor:pointer'; alertMainBox.appendChild(alertClose); document.body.appendChild(alertContainer); closeButton = document.getElementById('closeBox'); console.log(closeButton) closeButton.onclick = function(){ document.body.removeChild(document.getElementById('myAlertBox')); } }}
以下是具體要用時的代碼:
<!DOCTYPE HTML><html> <head> <meta http-equiv='content-type' content='text/html; charset=utf-8'> <title>Study</title> </head> <script type='text/javascript' charset='utf-8' src='http://www.leifengta.com.cn/bcjs/alert.js'></script> <body> <script type='text/javascript' charset='utf-8'> myAlert.alertbox('這是自定義alert框'); </script> </body></html>
用法很簡單,引入alert.js文件,要用時直接myAlert.alertbox('內(nèi)容');和使用alert一樣。
在這塊給大家提供個思路,供大家參考。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Android table布局開發(fā)實現(xiàn)簡單計算器2. 理解PHP5中static和const關(guān)鍵字3. jQuery 實現(xiàn)DOM元素拖拽交換位置的實例代碼4. php模擬實現(xiàn)斗地主發(fā)牌5. IntelliJ IDEA安裝插件的方法步驟6. phpstorm恢復(fù)默認設(shè)置的方法步驟7. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實現(xiàn)8. Python random庫使用方法及異常處理方案9. Vuex localStorage的具體使用10. .Net Core使用Coravel實現(xiàn)任務(wù)調(diào)度的完整步驟

網(wǎng)公網(wǎng)安備