小提琴: http://jsfiddle.net/ue7pq/
和等效的jQuery小提琴:
HTML:
<div class="project-box">
<img src="img/ifix.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of logos that we've made</p>
</div>
</div>
JS:
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img');
box = document.querySelectorAll('div.project-box div.hover-box');
imgWidth = img[0].offsetWidth;
imgHeight = img[0].offsetHeight;
console.log(imgWidth);
console.log(imgHeight);
box.style.width = imgWidth+'px';
box.style.height = imgHeight+'px';
};
我正在尝试使悬停盒与img具有相同的宽度和高度。我试图保持这个纯粹的javascript我犯了首先学习jQuery而不是JavaScript的错误所以现在我正在尝试自学JavaScript有一些问题。控制台日志说hoverbox未定义
console.log中的错误消息:
Uncaught ReferenceError: hoverBox is not defined main.js: 4
350
180
Uncaught TypeError: Cannot set property 'width' of undefined
答案 0 :(得分:4)
querySelectorAll
返回一个元素列表,但您将其视为引用单个元素。
我建议抓住项目框的列表,然后循环它们并调整每个项目框的大小。这样,如果页面上有多个,那么它们都会受到影响。这就像在jQuery中执行此操作:$('.project-box').each(function () { ... });
var project_boxes = document.getElementsByClassName('project-box');
for (var i = 0, len = project_boxes.length; i < len; i++) {
var img = project_boxes[i].querySelectorAll('img.thumbnail');
var box = project_boxes[i].querySelectorAll('div.hover-box');
if (box.length > 0 && img.length > 0) {
box[0].style.width = img[0].offsetWidth+'px';
box[0].style.height = img[0].offsetHeight+'px';
}
}
试一试:http://jsfiddle.net/EsJ4k/(注意:图片不存在,因此代码会产生0px的高度和宽度)
<强>文档强>
querySelectorAll
- https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll getElementsByClassName
- https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName 答案 1 :(得分:0)
<强> HTML 强>
<div class="project-box">
<img src="http://www.samdeveloper.com/images/sam_devloperr.jpg" class="thumbnail img-responsive">
<div class="hover-box">
<h2>TITLE</h2>
<p>Description of logos that we've made</p>
</div>
</div>
<强> CSS 强>
.project-box{position:relative; width:100%;}
.project-box .hover-box{position:absolute; bottom:0; width:100%; background-color:rgba(0,0,0,.5); display:none;}
<强>的jQuery 强>
$(function(){
$(".thumbnail").css("width","100%");
$(".project-box").hover(function(){
$(".hover-box").fadeIn(1000);
},function(){
$(".hover-box").fadeOut(1000);
});
});
的在线演示
答案 2 :(得分:-1)
window.onload = function(){
var project = document.getElementsByClassName('project-box');
img = project[0].getElementsByTagName('img')[0];
box = document.querySelectorAll('div.project-box, div.hover-box');
imgWidth = img.offsetWidth;
imgHeight = img.offsetHeight;
for(var i = 0; i < box.length;i++){
box[i].style.width = imgWidth+"px";
box[i].style.height = imgHeight+"px";
}
};