js -- 常见事件和操作

1、添加事件

添加事件方式
获取模块对象div
关联点击事件fun
实现事件功能

<body>
    <div style="width:200px; height:200px; background-color:red" onclick="alert('这是一个div')"></div>
    <div style="width:200px; height:200px; background-color:blue" onclick="test()"></div>
    <div id="div" style="width:200px; height:200px; background-color:green"></div>


<script>
function test() {
    console.log('花田里犯了错,说好,破晓前忘掉')
}
var odiv = document.getElementById('div')
// odiv.onclick = function () {
//     console.log('遥远的东方有一条龙')
// }
odiv.onclick = test
</script>
</body>

显示隐藏图片:
操作div的display属性,在block和none之间切换即可

<body>
    <div class="tu" style="display: block;">
        <img alt="可爱" src="feng.jpg" "="">
    </div>
    <button id="btn">消失</button>
    <button id="btn1" onclick="show()">出现</button>


<script>
// 显示和隐藏图片操作的是div的display属性,在block和none之间切换
var obutton = document.getElementById('btn')
obutton.onclick = function () {
    // 找到指定div,将其display属性修改为none
    var odiv = document.getElementsByClassName('tu')[0]
    odiv.style.display = 'none'
}

function show() {
    var odiv = document.getElementsByClassName('tu')[0]
    odiv.style.display = 'block'
}
</script></body>

this使用
在匿名函数中的this就是当前对象
在onclick=demo(this) 就是当前节点
修改内容
this.innerHTML = 'xxx'

<body>
    <div class="tang" style="width: 400px; height: 200px; background-color: red;">秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山</div>
    <div class="tang" style="width: 200px; height: 400px; background-color: blue;" onclick="demo(this)"></div>


<script>
    // 点击div,将宽度有200px修改为400px
    var odiv = document.getElementsByClassName('tang')[0]
    odiv.onclick = function () {
        console.log(this)
        // this就是odiv
        this.style.width = '400px'
        // 给div添加内容
        this.innerHTML = '秦时明月汉时关,万里长征人未还,但使龙城飞将在,不教胡马度阴山'
    }

    function demo(obj) {
        // 这里面的this是window,在js里面写的所有的函数都是window的函数,调用demo其实就是  window.demo()
        console.log(this)
        // var odiv = document.getElementsByClassName('tang')[1]
        obj.style.height = '400px'
    }
</script></body>

切换背景色

<body>
    <div id="bai" style="width: 300px; height: 300px; background-color: red;"></div>


<script>
var odiv = document.getElementById('bai')
odiv.onclick = function () {
    // 先获取div的背景色
    color = this.style.backgroundColor
    if (color == 'red') {
        this.style.backgroundColor = 'yellow'
    } else {
        this.style.backgroundColor = 'red'
    }  
}
</script></body>

表单内容控制

<script>
    // clear是关键字,不能使用函数名
function cleara(obj) {
    // console.log('clear')
    if (obj.value == "请输入用户名") {
        obj.value = ''
    }
}
function recover(obj) {
    if (obj.value == '') {
        obj.value = '请输入用户名'
    }
}
var oinput = document.getElementById('ip')
oinput.onfocus = function () {
    // 判断要不要清空
    if (this.value == "请输入用户名") {
        this.value = ''
    }
}
oinput.onblur = function () {
    // 判断内容是不是为空,如果为空变成下面这个
    if (this.value == '') {
        this.value = '请输入用户名'
    }
}
</script>

2、onload函数

window的事件,windows.onload = function () {} 是在整个文档加载完毕之后执行,但是自己写的onclick的点击函数不能写到onload里面,因为内部函数只能在内部使用,不能再外部使用
如果实在是想用window.lala = function () {}

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>onload函数</title>
    <script>
        // var a = '岳云鹏'
        // demo()
        // onload是window的事件,意思就是等文档加载完毕之后来执行这个代码
        window.onload = function () {
            // var odiv = document.getElementById('kong')
            // console.log(odiv)
            // odiv.onclick = function () {
            //     this.style.backgroundColor = 'cyan'
            // }

            
        }
        function demo(obj) {
            obj.style.backgroundColor = 'cyan'
        }
        
    </script>
</head>

<body>
    <div id="kong" style="width: 300px; height: 300px; background-color: cyan;" onclick="demo(this)"></div>

<script>
    
    // console.log(a)
    // function demo() {
    //     console.log('你喜欢岳云鹏的相声吗?')
    // }
</script>

<script>
    // alert(a)
    // demo()

    function test() {
        // function lala() {
        //     console.log('这是一个内部函数')
        // }
        // lala()
        window.lala = function () {
            console.log('这是lala函数')
        }
    }
    test()
    // test.lala()
    lala()
</script></body>

3、选项卡

手动添加下标

<style>
    button {
        width: 200px;
        height: 100px;
        font-size: 40px;
        background-color: pink;
        margin-left: 50px;
        display: inline-block;
    }
    div {
        width: 970px;
        height: 600px;
        font-size: 50px;
        background-color: yellow;
        margin-left: 50px;
        margin-top: 50px;
        display: none;
    }
    .active {
        font-size: 50px;
        background-color: blue;
    }
    .show {
        display: block;
    }
</style>
<body>
    <button onclick="dudu(this, 0)">周杰伦</button>
    <button onclick="dudu(this, 1)">王力宏</button>
    <button onclick="dudu(this, 2)">张学友</button>
    <button class="active" onclick="dudu(this, 3)">刘德华</button>
    <div>稻香、菊花台、发如雪、青花瓷、七里香、霍元甲、双节棍、简单爱、千里之外、听妈妈的话</div>
    <div>花田错、龙的传人、唯一</div>
    <div>慢慢、吻别、一千个伤心的理由</div>
    <div class="show">谢谢你的爱、冰雨、天意、忘情水</div>


<script>
    // 得到所有的button
    var abuttons = document.getElementsByTagName('button')
    // 得到所有的div
    var adivs = document.getElementsByTagName('div')
    function dudu(obj, index) {
        // 先将所有的button的class属性设置为空
        for (var i = 0; i < abuttons.length; i++) {
            abuttons[i].className = ''
            adivs[i].className = ''
        }
        // 给指定的button添加样式
        obj.className = 'active'
        // 给指定的div添加样式
        adivs[index].className = 'show'
    }
</script></body>

自动添加下标

<style>
    button {
        width: 200px;
        height: 100px;
        font-size: 40px;
        background-color: pink;
        margin-left: 50px;
        display: inline-block;
    }
    div {
        width: 970px;
        height: 600px;
        font-size: 50px;
        background-color: yellow;
        margin-left: 50px;
        margin-top: 50px;
        display: none;
    }
    .active {
        font-size: 50px;
        background-color: blue;
    }
    .show {
        display: block;
    }
</style>

<body>
    <button class="active">李白</button>
    <button>杜甫</button>
    <button>李商隐</button>
    <button>杜牧</button>
    <div class="show">将敬酒,蜀道难,菩萨蛮,月下独酌,梦游天姥吟留别,宣州谢朓楼饯别校书叔云</div>
    <div>石壕吏,潼关吏,新安吏,新婚别,无家别,垂老别</div>
    <div>马嵬,瑶池,无题,贾师,随师东</div>
    <div>清明,赤壁,秋夕,泊秦淮</div>


<script>
// 得到所有的button
var abuttons = document.getElementsByTagName('button')
var adivs = document.getElementsByTagName('div')
// 循环button数组,给里面每一个button添加点击事件
for (var i = 0; i < abuttons.length; i++) {
    // 给指定的button手动添加一个属性,用来保存是第几个button
    abuttons[i].index = i
    abuttons[i].onclick = function () {
        // 首先清掉所有button和div上面的class
        for (var j = 0; j < abuttons.length; j++) {
            abuttons[j].className = ''
            adivs[j].className = ''
        }
        // 给指定的button添加样式
        this.className = 'active'
        // console.log(i)
        // 给指定的div添加样式
        adivs[this.index].className = 'show'
    }
}
</script></body>

4、定时器

定时器:分为两种,一种是周期性定时器,一种是一次性定时器
周期性:每隔5s执行一次函数
一次性:几秒之后执行一次函数,执行完毕定时器结束
var timer = setTimeout(fn, 5000)5000ms之后执行fn一次。然后结束

<body>
    <div id="baby">
        <img height="800" alt="气质美女" src="meinv.jpg">
    </div>
    <button id="btn">计时开始</button>


<script>
    var odiv = document.getElementById('baby')
    var obtn = document.getElementById('btn')
    // timer就是一个定时器
    var timer = setTimeout(function () {
        odiv.style.display = 'none'
    }, 5000)

    obtn.onclick = function () {
        // 清除timer这个定时器
        clearTimeout(timer)
    }
</script></body>

销毁定时器 clearTimeout(timer)

<body>
    <button onclick="demo()">一行白鹭上青天</button>

<script>
    var timer = setInterval(function () {
        console.log('两个黄鹂鸣翠柳')
    }, 5000)

    function demo() {
        clearInterval(timer)
    }
</script></body>

小应用:背景闪烁

<body>
    <div id="lala" style="width: 300px; height: 300px; background-color: yellow;"></div>


<script>
    var odiv = document.getElementById('lala')
    setInterval(function () {
        color = odiv.style.backgroundColor
        if (color == 'red') {
            odiv.style.backgroundColor = 'yellow'
        } else {
            odiv.style.backgroundColor = 'red'
        }
    }, 50)
</script></body>
闪.gif

计数器

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>计数器</title>
    <style>
    div {
        width: 100%;
        height: 300px;
        line-height: 300px;
        text-align: center;
        font-size: 300px;
        background-color: pink;
    }
    </style>
</head>

<body>
    <div id="dudu">2</div>


<script>
var odiv = document.getElementById('dudu')
// 定义一个全局变量,用来保存定时器对象
var timer = null
// 定义一个全局的计数器
var i = 0
odiv.onmouseover = function () {
    timer = setInterval(function () {
        i++
        // 设置div的内容
        odiv.innerHTML = i
    }, 1000)
}

odiv.onmouseout = function () {
    clearInterval(timer)
}
</script></body>

5、获取非行内样式

IE浏览器获取非行内样式方式
obj.currentStyle['name']
火狐和谷歌获取方式
getComputedStyle(odiv, null)['width']
获取非行内样式的兼容性写法

    function getStyle(obj, name) {
        return obj.currentStyle ? obj.currentStyle[name] : getComputedStyle(obj, null)[name]
    }

6、BOM操作

    window.setTimeout,window.setInterval
    window.alert\window.confirm
    window.open
    window.history(back、go)
        history.go(1)   去往前一个网址
        history.go(2)   去往后一个网址
        history.back()  倒退一个网址
    location  
        href : 读取得到当前的url,设置跳转到指定的url
        reload() : 刷新整个页面

7、select下拉框和oninput事件

onchange : 事件,用户点击下拉框触发
selectedIndex : 用户点击的option的下标,下标从0开始
options : osel.options 可以得到所有的option对象,这是一个数组
input框的oninput事件,只要内容改变,就会触发

<body>
    <select name="刺客" id="sel">
        <option value="1">阿珂</option>
        <option value="2">兰陵王</option>
        <option value="3">孙悟空</option>
        <option value="4">赵云</option>
        <option value="5">李白</option>
    </select>
    <input id="ip" type="text">


<script>
    var osel = document.getElementById('sel')
    osel.onchange = function () {
        // alert('触发')
        // alert(osel.selectedIndex)
        alert(osel.options[osel.selectedIndex].innerHTML)
    }

    var oinput = document.getElementById('ip')
    oinput.oninput = function () {
        console.log(this.value)
    }
</script></body>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 230,048评论 6 542
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 99,414评论 3 429
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 178,169评论 0 383
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 63,722评论 1 317
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 72,465评论 6 412
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 55,823评论 1 328
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 43,813评论 3 446
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 43,000评论 0 290
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 49,554评论 1 335
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 41,295评论 3 358
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 43,513评论 1 374
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 39,035评论 5 363
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 44,722评论 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 35,125评论 0 28
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 36,430评论 1 295
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 52,237评论 3 398
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 48,482评论 2 379

推荐阅读更多精彩内容

  • 工厂模式类似于现实生活中的工厂可以产生大量相似的商品,去做同样的事情,实现同样的效果;这时候需要使用工厂模式。简单...
    舟渔行舟阅读 7,805评论 2 17
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,581评论 1 45
  • 今天谈一下RxSwift中的组合操作,和RAC一样。可以参照RAC理解。 Combination Operator...
    AKyS佐毅阅读 2,677评论 0 2
  • 决定开始真正用心静下心来读一本书了,好好阅读,好好感受吧,愿你终有一日可以成为那个举止谈吐富有诗书的女孩.
    destinyenna阅读 327评论 0 0
  • 子木一早来到了顺旺房产公司,来的时候还没有开门,子木一个人在门口等着,过来大概有十分钟,子木看到一个男的走了过来,...
    多留阅读 679评论 0 0