Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将一系列元素的宽度设置为div之前的图像宽度_Javascript_Jquery_Html_Css - Fatal编程技术网

Javascript 如何将一系列元素的宽度设置为div之前的图像宽度

Javascript 如何将一系列元素的宽度设置为div之前的图像宽度,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我试图为一系列标题设置相同的宽度,因为图像正好位于标题之前 我有这个HTML: <div class="theparent"> <img src="pic.jpg"/> <div class="caption"> hello </div> <div> <div class="theparent"> <img src="pic2.jpg"/> <div class="

我试图为一系列标题设置相同的宽度,因为图像正好位于标题之前

我有这个HTML:

<div class="theparent"> 
<img src="pic.jpg"/>
<div class="caption">
        hello
    </div>
<div>
<div class="theparent">
    <img src="pic2.jpg"/>
    <div class="caption">
        hello
   </div>
<div>
<div class="theparent">
<img src="pic3.jpg"/>     
<div class="caption">
        hello
     </div>
<div>

请不要建议我使用css,在我的情况下,我不得不使用JS。谢谢!

您缺少选择器上的
更改此项:

$(this).find("caption").css("width", myWidth);
对此

$(this).find(".caption").css("width", myWidth);

您可以在css中执行此操作。只需将标题的宽度设置为100%,如下所示:

.caption{
     width: 100%;
}
它将自动获取父对象的宽度。

如何

$(".caption").each(function(){
    $(this).css("width", $(this).prev('img').css("width"));
});

(根据您的需要添加SetTimeOut逻辑…

CSS如何
.caption{width:100%;}
为什么不使用CSS:.caption{width:100%}您的代码似乎是错误的,标题前缺少点。$(此)。查找(.caption”).CSS(“width”,myWidth);div不是默认为100%宽吗?我遗漏了什么吗?我的情况非常复杂,我被迫使用js而不是像100%宽这样简单的东西。但是谢谢!不应该是必要的,div默认为100%宽…除非我们没有被告知。谢谢,我已经做了更正,但这不是解决方案关于我的问题:)
$(".caption").each(function(){
    $(this).css("width", $(this).prev('img').css("width"));
});