javascript - 如何修复自定义警报功能

标签 javascript html css

我一直在试验自定义警报,这是我到目前为止想出的:

window.CustomAlert = function(parameters) {
    var alert = document.createElement("div");
    var title = parameters.title !== undefined ? parameters.title : "ALERT!";
    var message = parameters.message !== undefined ? parameters.message : "Hello World!";
    var type = parameters.type !== undefined ? parameters.type : "";
    var color = type === "info" ? "#2196F3" : type === "success" ? 
        "#4CAF50" : type === "warning" ? "#ff9800" : type === "danger" ? "#f44336" : "#000000";
    document.body.appendChild(alert);
    alert.style.margin = "auto";
    alert.style.position = "absolute";
    alert.style.top = "0";
    alert.style.left = "0";
    alert.style.border = "1px solid black";
    alert.style.maxHeight = "350px";
    alert.style.width = "99.8%";
    alert.style.minHeight = "70px";
    alert.style.color = "white";
    alert.style.background = "#fff";
    alert.style.fontFamily = "sans-serif";
    alert.style.fontWeight = "bold";
    alert.style.overflow = "auto";
    alert.innerHTML = `
        <span style="float:right;font-size:25px;cursor:pointer;color:black;padding:7px;background:red" 
            onclick="this.parentElement.parentNode.removeChild(this.parentElement)"
        >&times;</span>

        //title
        <div style="background:` + color + `;padding:15px;height:30%">
            <p>` + title + `</p>
        </div>
        //message
        <div style="background:#ccc;padding:15px;height:80%">
            <p>` + message + `</p>
        </div>
    `;
};

CustomAlert({
    title: "LOG:",
    message: "Document initialized.",
    type: "info"
});

...那么就会出现3个问题: 1) 标题和消息框之间会有烦人的间隙; 2)span函数只关闭标题框;和 3) 标题和消息的高度不起作用。 我该如何解决这些问题?

最佳答案

由于你似乎是 JS 的新手,我将首先给你一些如何改进代码的指导:

  • 使用 CSS 作为警报样式,不要使用内联样式。它为您的代码添加了太多行
  • 将警报类型定义为类似枚举的对象:

    const CustomAlertType = {
        info: {color:"#2196F3"},
        success: {color:"#4CAF50"},
        warning: {color:"#ff9800"},
        danger: {color:"#f44336"},
        defaultValues: {color:  "#000000"}
    }
    
  • 由于您使用的是字符串模板,您可以这样做:value=${variable}
  • 不要附加alert在你设置它之前 innerHTML .它对浏览器有影响,因为它需要验证 DOM 树。就此而言,尽量不要使用 innerHTML除非你需要
  • 不要像这样在 HTML 中使用回调:<elm onclick=...相反,您可以这样做:alert.querySelector("span.close").addEventListener("click", .之后,HTML 缩小了很多并且更易于阅读:

    alert.innerHTML = `
        <span class="close">&times;</span>
        <div class="title" style="background:${typeObj.color};">
            <p>${title}</p>
        </div>
        <div class="message">
            <p>${message}</p>
        </div>
    `;
    
  • 当警报关闭时,您可能应该有一个回调,例如。 parameters.onclose
  • 作为特殊待遇,我添加了一个如何在异步函数中使用警报回调的示例,因此它的行为几乎类似于 window.alert

这些修复后的最终代码:

/**
 * @enum
 * Defines properties for different alert types
 *
**/
const CustomAlertType = {
    info: {color:"#2196F3"},
    success: {color:"#4CAF50"},
    warning: {color:"#ff9800"},
    danger: {color:"#f44336"},
    defaultValues: {color:  "#000000"}
}

window.CustomAlert = function(parameters) {
    var alert = document.createElement("div");
    alert.classList.add("customAlert");
    var title = parameters.title !== undefined ? parameters.title : "ALERT!";
    var message = parameters.message !== undefined ? parameters.message : "Hello World!";
    // Type must be string, of not string use default
    var type = typeof parameters.type == "string" ? parameters.type : "defaultValues";
    // If the type is not valid, it will fall back to default
    const typeObj = CustomAlertType[type] || CustomAlertTyle.defaultValues;


    alert.innerHTML = `
        <span class="close">&times;</span>
        <div class="title" style="background:${typeObj.color};">
            <p>${title}</p>
        </div>
        <div class="message">
            <p>${message}</p>
        </div>
    `;
    // After close is clicked, alert is destroyed and callback is called
    alert.querySelector("span.close").addEventListener("click", function() {
        alert.parentNode.removeChild(alert);
        // If there is a close callback, call it so that code can continue
        if(typeof parameters.onclose == "function") {
            parameters.onclose();
        }
    });
    document.body.appendChild(alert);
};
// Allows to await on alert being closed in `async` functions
function CustomAlertAsync(parameters) {
    return new Promise((resolve, reject)=>{
        parameters.onclose = resolve;
        CustomAlert(parameters);
    });
}
// Example of for loop that waits on alerts to be confirmed
(async ()=>{
    for(let i=0; i<5; ++i) {
        await CustomAlertAsync({title:"for() loop", type: "info", message: "Message #"+(i+1)});
    }
})();

CSS:

body {
  height: 800px;
}

.customAlert {
  margin: auto;
  position: fixed;
  top: 0px;
  left: 0px;
  border: 1px solid black;
  max-height: 350px;
  width: 99.8%;
  color: white;
  background-color: white;
  font-family: sans-serif;
  font-weight: bold;
  overflow: auto;
}
.customAlert .close {
  float: right;
  font-size: 25px;
  cursor: pointer;
  color: black;
  padding: 7px;
  background: red;
  width: 1em;
  height: 1em;
  text-align: center;
}
.customAlert .title {
  padding: 15px;
  height: 2em;
}
.customAlert .message {
  background: #ccc;
  padding: 15px;
}

演示:https://jsfiddle.net/Darker/o5rbLya9/27/

虽然我不太清楚你的意思是什么:

3) The heights of the title and message don't work

我真的认为你应该在 上单独提问+ 这将只使用带有 CSS 的 HTML 示例,而没有 javascript 部分。您可以使用开发工具获取警报的 HTML。

关于javascript - 如何修复自定义警报功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57671792/

相关文章:

javascript - 验证动态表单

javascript - HTML 5 UI 组件标记库(如 jQuery Mobile)

html - 表格中的字体颜色不继承自父 div

html - Bootstrap - 重复图案覆盖背景颜色超大屏幕

javascript - 隐藏元素后滚动到顶部不起作用 (jQuery)

html - 在 FireFox 的 CSS 计算中额外 +4px

css - Flexbox 垂直对齐溢出

javascript - "lang.link.toolbar is null or not an object"在 IE7 中使用 CKeditor

javascript - 按下特定列表的按钮后使用ajax更新特定列表<li>

javascript - 使用 Mongoose 中间件改变请求正文