码迷,mamicode.com
首页 > Web开发 > 详细

js中的事件添加和程序

时间:2018-07-10 11:16:15      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:判断   else   on()   width   点击事件   程序   bsp   基本   原则   

事件的基本使用方式:

事件源.事件类型 = function(){事件触发后的操作};

点击事件:click;

在js中点击事件使用时前面要加on,为onclick;

例:点击btn按钮给box添加样式;

btn.onclick = funciton(){

  box.style.width = ‘100px‘;

  box.style.height = ‘100px‘;

  box.style.backgroundColor = ‘red‘;

};

移入移出事件

mouseover :鼠标移入事件;

 box.onmouseover = function(){

  this.style.backgroundColor = ‘blue‘;

}

mouseout :鼠标移出事件;

box.onmouseout = function(){

   this.style.backgroundColor = ‘red‘;

}

 

 

小例题;

  点击按钮实现页面变色的效果;

1、首先获取元素 btn 按钮 ;

2、事件绑定 btn.onclick = funciton(){};

3、在{}中写事件驱动程序;

  var btn = document.getElementById(‘btn‘);

  var flag = true;  //为了实现上述效果我们采用一种简便方式;开闭原则;

  btn.onclick = function (){

    if(flag){//由于上面已经给flag赋值了true;所以此次判断可以进入;

      dcoument.body.className = ‘black‘;//给body赋值白色;

      btn.innerText = ‘变成白色‘;//给变按钮的内容;

      flag = false;//将flag设为false;让下次点击不能进入if循环,只能进入else;

    }else{

      document.body.className = ‘white‘;

      btn.innerText = ‘变成黑色‘;

      flag = true;//当页面设置为黑色时 给flag设置为true;让下次点击不能进入

            else只能进入if循环;

    }

  }

 

js中的事件添加和程序

标签:判断   else   on()   width   点击事件   程序   bsp   基本   原则   

原文地址:https://www.cnblogs.com/qiweile/p/9287079.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!