1

小提琴:http: //jsfiddle.net/ue7pq/

和等效的 jQuery 小提琴:

http://jsfiddle.net/Ldn9P/

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 有一些问题。控制台日志说悬停框未定义

console.log 中的错误消息:

Uncaught ReferenceError: hoverBox is not defined main.js: 4
350 
180 
Uncaught TypeError: Cannot set property 'width' of undefined
4

3 回答 3

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)

文档

于 2013-11-13T05:08:06.590 回答
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);
    });
});

单击此处的在线演示

于 2013-11-13T05:21:40.777 回答
-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";
}
};
于 2013-11-13T04:58:13.197 回答