您的位置:首页 > Web前端 > JavaScript

玩转JavaScript的Web API : 原生js操控显式HTML元素

2016-05-03 18:15 537 查看
之前做过两道前端,阿里和网易各一道。下文内容和解题的核心并无关系,只是当时想了解jQuery那么处理原生js的原理是什么,所以小结一下。

题目一:判断两个矩形元素是否重叠。

开始无尽的跑偏。。。。

Html元素都是HTMLElement实例,下例将div换成script、html都成立。

HTMLElement继承自Element,Element继承自Node。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#parent{
width: 300px;
height: 300px;
margin-left: 100px;
}
#div1{
width: 200px;
height: 200px;
background: red;
}
#div2{
width: 300px;
height: 300px;
background: blue;
position: relative;
top: -200px;
}
</style>
</head>
<body>
<div id='parent'>
<div id = 'div1'>
</div>
</div>
<div id = 'div2'>
</div>
<script>
var div1 = document.querySelector('#div1');
var div2 = document.querySelector('#div2');

function isOverlap(e1,e2){
var overlapX = false,
overlapY = false,

top1 = e1.offsetTop,
top2 = e2.offsetTop,

left1 = e1.offsetLeft,
left2 = e2.offsetLeft,

height1 = e1.offsetHeight,
height2 = e2.offsetHeight,

width1 = e1.offsetWidth,
width2 = e2.offsetWidth;

if(top1<top2 ){
if(top1+height1>top2){
overlapY = true;
}
} else {
if(top2+height2>top1){
overlapY = true;
}
}

if(left1>left2 ){
if(left1+width1>left2){
overlapX = true;
}
} else {
if(left2+width2>left1){
overlapX = true;
}
}

return overlapX && overlapY;
}

if(isOverlap(div2,div1)){
alert('重叠了');
} else {
alert('没重叠');
}

</script>
</body>
</html>


View Code

题目二:可以说忘了吗^_^#,大致和通用事件注册,事件代理,列表选择有关。

这里我只关心如何改变一个div的样式

Element的ClassName属性以字符串的形式保存拥有的class名称,多个class名空格隔开。

jQuery提供了addClass、removeClass、toggleClass操作元素的class。如果想使用原生js,并且通过类来改变div样式,难道必须进行字符串操作吗?

HTML5给Element带来一个新属性——classList,操作示例如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.size{
width: 100px;
height: 100px;
}
.blue{
background: blue;
}
.red{
background: red;
}
</style>
</head>
<body>
<div class="size blue">
</div>
<script>
var div = document.querySelector('div');
console.log(div.className); //"size blue"

div.classList.add('red');
console.log(div.className); //"size blue red"

div.classList.remove('red');
console.log(div.className); //"size blue"

if(!div.classList.contains('red')){
console.log('类已被移除');
}

div.onclick = function(){
div.classList.toggle('red');
};
</script>
</body>
</html>


随着越来越强大的新标准推行,原生js也简洁起来咯~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: