如何使用 position:relative;
动态更改元素的大小?我尝试使用 width:45%;
使其始终占容器的 45%,但是当更改浏览器大小时,我发现它仍然是最初加载的大小,当我刷新时页面,它变小了,但是当我把页面变大时它仍然变小了。
我会接受 jQuery 和/或 Javascript 解决方案,但更喜欢 CSS。此外,如果这似乎是我的代码的错误,而不是由于 position:relative;
的基本工作方式,请告诉我,我会立即将我的代码添加到帖子中。
编辑:添加代码
<div id="container">
<p class="caption">
<img class="thumbnail" src="http://i.ytimg.com/vi/NpEaa2P7qZI/maxresdefault.jpg" alt="Placeholder"> <span>
<b>This is the Caption's Title</b>
This is the caption's description
</span>
</p>
查看其余here
它似乎在 fiddle 中起作用,不确定为什么它在客户端不起作用。
最佳答案
您的问题是因为在页面加载时执行了 javascript。
当它遍历您的 .captions
时,会将内联样式设置为具有宽度和高度的 .caption
。
这部分:
...
$(this)
// Add the following CSS properties and values
.css({
// Height equal to the height of the image
"height": $(this).children("img").height() + "px",
// Width equal to the width of the image
"width": $(this).children("img").width() + "px"
})
...
jQuery .css
设置内联样式,因此当您调整窗口大小时不会发生任何变化,因为 img
具有静态宽度和高度。
您正在尝试使用 !important
声明在您的 CSS 中覆盖它,但内联样式胜出。
去掉这段代码好像可以解决问题,但不知道会不会引入其他问题。
我还将这段代码放在它自己的名为 setCaptionSize()
的函数中,并在页面加载时触发它,并将它附加到窗口调整大小事件。
$(function () {
setCaptionSize();
$(window).resize(setCaptionSize);
});
我还将悬停事件从 setCaptionSize
中移出,这样它就不会被多次绑定(bind)。
查看此 Fiddle演示
关于javascript - 相关元素的 CSS 动态定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31216240/