python测试开发JavaScript程序员

在浏览器中用JS实现常见弹出框

2017-02-27  本文已影响783人  史密斯_Du

JS常见的弹出框(非常之简单)

JS中浏览器常用的弹出框有三种:

下面我们来看一下具体在代码中是怎么实现的
HTML&CSS:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>三种JS弹出框</title>
    <style>
        *{
            margin:0;
            padding:0;
            list-style: none;
            color: steelblue;
        }
        .box{
            margin:20px auto;
            width:300px;
            padding:20px;
            border:1px solid steelblue;

        }
        .box div{
            height:32px;
            margin:10px auto;
            line-height: 32px;
        }
        .box div span{
            display: inline-block;
            width:50px;
        }
        .box div input{
            width:188px;
            height: 30px;
            padding: 0 10px;
            border: 1px solid #ddd;
        }
        .box .submit{
            width: 150px;
            margin-top:30px;
            text-align: center;
            background: steelblue;
            color: #fff;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div class="box">
    <div>
        <span>姓名:</span>
        <input type="text" id="userName">
    </div>
    <div>
        <span>性别:</span>
        <input type="text" id="userSex">
    </div>
    <div>
        <span>爱好:</span>
        <a id="like" style="color: #DDD;">这里稍后再看</a>
    </div>
    <div class="submit" id="submit">提交</div>
</div>
</body>
</html>
<script>
 var nameInfo = document.getElementById('userName'),
        sexInfo = document.getElementById('userSex'),
        submit = document.getElementById('submit'),
        like = document.getElementById('like');
</script>

无添加JS弹框效果的静态页面


下面添加JS来分别看看三个不同的效果:

 submit.onclick =function () {
        alert('您的姓名是'+nameInfo.value + '\n' + 
              '您的性别是'+sexInfo.value)
// 此处的 '\n' 是起换行显示作用
}

浏览器中预览效果: 点击提交后出现弹窗


   submit.onclick =function () {
        confirm('请问您的姓名是'+nameInfo.value +'吗?' + 
         '\n' + '您的性别是'+sexInfo.value+'吗?')
      } 
//注:(此处还可以申明一个变量 flag)
   submit.onclick =function () {
       var flag = confirm('请问您的姓名是'+nameInfo.value +'吗?' + 
         '\n' + '您的性别是'+sexInfo.value+'吗?')
       console.log(flag); 
      } 

浏览器中预览效果: 点击提交后出现弹窗(
//在弹出框中点击确定,返回true
//在弹出框中点击取消,返回false)


浏览器中预览效果: 点击提交后出现弹窗(如果用户点击确认,那么返回值为输入的值。如果用户点击取消,那么返回值为 null。)
![](http://upload-images.jianshu.io/upload_images/4596776-7f345bbb5ed4c780.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


相信看完本文并且自行在浏览器中测试的同学应该已经能初步掌握本文了javascript中的三种弹出对话框,分别是alert()方法,confirm()方法,prompt()方法了,现在回忆回忆是否已经掌握了呢?
如有异议,欢迎指正,一起交流进步~

上一篇下一篇

猜你喜欢

热点阅读