JS能否获取动态class的宽度并赋值给高度,目的是实现响应式正方形,附HTML和CSS

十分感谢,初步的想法实现了,但是只能赋值给一个id,而缩略图有很多。

为了最终效果,我对代码做了调整,目前的情况是这样,能不能赋高度值给公用的class,这样所有的图片就都获取高度了:

HTML:

<div id="thumbnailbox">

<a href="post_1.html" title="缩略图1"> <div class="thumbnail" id="1"></div> </a> </div>

<a href="post_2.html" title="缩略图2"><div class="thumbnail" id="2"></div></a>
...
</div>

一行一共四个div,自动撑满浏览器,css部分:

#humbnailbox {
width: 100%;
margin: 0 auto;
clear: both;
}
.thumbnail {
width: 25%;
float: left;

background-position: center center;
background-repeat: no-repeat;
background-size: cover;
}
#1 {
background-image: url(../images/1.jpg);
}
#2 {
background-image: url(../images/2.jpg);
}
......

感谢了,我追加50分给

你这样的写的话 不先赋值给thumbnail统一的高度的话恐怕页面会显得参差不齐而不是你想的4块模块平均撑开页面,还有你是把图片写进div你当背景,那就不需要js来处理这个问题。

<style>
#thumbnailbox{position: absolute;left:0;top:0;width:100%;height:100%;}
#thumbnailbox a{width:50%;height:50%;display:block;position:absolute;left:0;top:0;}
#thumbnailbox a.bg1{background:url(../images/1.jpg) 50% 50% no-repeat;}
#thumbnailbox a.bg2{left:50%;background:url(../images/2.jpg) 50% 50% no-repeat;}
#thumbnailbox a.bg3{top:50%;background:url(../images/3.jpg) 50% 50% no-repeat;}
#thumbnailbox a.bg4{left:50%;top:50%;background:url(../images/4.jpg) 50% 50% no-repeat;}
</style>
<div id="thumbnailbox">
<a href="post_1.html" title="缩略图1" class="thumbnail bg1"></a>
<a href="post_1.html" title="缩略图1" class="thumbnail bg2"></a>
<a href="post_1.html" title="缩略图1" class="thumbnail bg3"></a>
<a href="post_1.html" title="缩略图1" class="thumbnail bg4"></a>
</div>

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-06-02
为什么缩略图非要用背景图片的方式?背景图片是无法设置宽度的。直接把图片写入div中不可以吗?然后给IMG设置css就可以了呀。