html代码:
<div class="box green">I'm green!</div>
<div class="box blue">I'm blue!</div>
<div class="box orange">I'm orange!</div>
这里的 CSS 代码:
.green { background-color: green; }
.blue { background-color: dodgerblue; }
.orange { background-color: orangered; }
JavaScript 代码在这里使用对象字面量语法:// 想要对 box2 和 box3 应用相同的效果
var box1 = {
color: 'Green',
number: 1,
clickMe: function () {
var green = document.querySelector('.green');
var self = this;
green.addEventListener('click', function () {
var str = 'This is box number ' + self.number + ' and it is ' + self.color;
alert(str);
});
}
}
box1.clickMe();