我的文档中有几个div类。我想点击任何一个div类并获得div元素的全屏。目前我只能使用document.getElementById("1")
进行此操作。而且我不想使用jQuery只是纯JavaScript。
<html !DOCTYPE>
<head>
<title>Javascript trening</title>
<style>
.videoFrame{
width:100px;
height:100px;
margin-bottom:10px;
background:#000;
}
.videoFrame:nth-child(2){
background:#cadaef;
}
.videoFrame:nth-child(3){
background:#aed924;
}
.videoFrame:nth-child(4){
background:#491356;
}
</style>
</head>
<body>
<div class="videoFrame">
</div>
<div class="videoFrame" id="1">
</div>
<div class="videoFrame">
</div>
<div class="videoFrame">
</div>
<script type="text/javascript">
var oneDoc = document.getElementById("1");
oneDoc.onclick = fullScreenDiv;
function fullScreenDiv(){
if(oneDoc.requestFullscreen){
oneDoc.requestFullscreen();
} else if (oneDoc.mozRequestFullScreen){
oneDoc.mozRequestFullScreen();
} else if(oneDoc.webkitRequestFullscreen){
oneDoc.webkitRequestFullscreen();
} else if (select.msRequestFullscreen) {
oneDoc.msRequestFullscreen();
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
您可以在body
或任何其他父元素上定义点击处理程序。单击任何子元素时会触发该处理程序。然后只需检查目标元素,看看它是否具有您想要触发的类。
下面有一个例子。该事件在任何videoFrame
元素上触发,但不在另一个元素上触发。
var body = document.querySelector("body");
body.addEventListener("click", function(e) {
var target = e.target;
if (hasClass(target, "videoFrame")) {
fullScreenDiv(target);
} else {
alert("not this one");
}
})
function hasClass(element, cls) {
return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
function fullScreenDiv(oneDoc){
if(oneDoc.requestFullscreen){
oneDoc.requestFullscreen();
} else if (oneDoc.mozRequestFullScreen){
oneDoc.mozRequestFullScreen();
} else if(oneDoc.webkitRequestFullscreen){
oneDoc.webkitRequestFullscreen();
} else if (select.msRequestFullscreen) {
oneDoc.msRequestFullscreen();
}
}
.videoFrame{
width:100px;
height:100px;
margin-bottom:10px;
background:#000;
}
.videoFrame:nth-child(2){
background:#cadaef;
}
.videoFrame:nth-child(3){
background:#aed924;
}
.videoFrame:nth-child(4){
background:#491356;
}
.notThisOne {
width:100px;
height:100px;
margin-bottom:10px;
background:#F00;
}
<div class="videoFrame">
</div>
<div class="videoFrame" id="1">
</div>
<div class="videoFrame">
</div>
<div class="videoFrame">
</div>
<div class="notThisOne"></div>
答案 1 :(得分:0)
document.getElementsByClassName('videoFrame')[index]
其中index
是您要访问的div(从0开始),所以在您的情况下索引将是一个
文档对象上有很多方法可以选择DOM元素,除getElementById
和querySelector
之外的所有方法都返回一个nodeList(类似于数组)的元素,所以你必须访问通过指定索引
如果您想为所有这些div添加一个事件处理程序,则必须遍历此nodeList:
var videoFrames = document.getElementsByClassName('videoframe');
for(int i = 0; i < videoFrames.length; i++) {
videoFrames[i].onclick = //event handler
}