2016-05-13 70 views
0

这是我的代码..我需要使用jquery在子元素中设置宽度值?

<div style="width: 89px"> 
    <span class="copyText">This is some text to copy.</span> 
    <span>Can't copy </span> 
    <span class="copyText1">And this is yet more text.</span> 
</div> 

我需要的div元素的宽度并添加+6 PX和这个值设置为这个跨度只有<span>Can't copy </span>

,如果可能请给我的解决方案。 。

+0

文档结构不清晰的我。我应该改变第二个跨度吗?还是跨班没?或者完全跨越这个文本?也不清楚为什么设置跨度的宽度,如果父div更窄。将不会有效果。 –

回答

0

当你标记一个jQuery ..你只需要

var divWidth = $('div').outerWidth(); 
$('div > span:nth-child(2)').css('width' , divWidth + 6 +'px'); 

演示

var divWidth = $('div').outerWidth(); 
 
$('div > span:nth-child(2)').css('width' , divWidth + 6 +'px');
div{ 
 
    background : #eee; 
 
} 
 

 
span{ 
 
    padding : 5px 0px; 
 
} 
 

 
span:not([class^=copyText]){ 
 
    background : #005eff; 
 
    color : #fff; 
 
    display : block; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div style="width: 89px"> 
 
    <span class="copyText">This is some text to copy.</span> 
 
    <span>Can't copy </span> 
 
    <span class="copyText1">And this is yet more text.</span> 
 
</div>

0

试试这个:

<div class="myDiv" style="width: 89px"> 
    <span class="copyText">This is some text to copy.</span> 
    <span class="setSpan">Can't copy </span> 
    <span class="copyText1">And this is yet more text.</span> 
</div> 

的Jquery:

var width = parseInt($(".myDiv").css("width").replace("px","")) + 6; 
$(".setSpan").css("width",width); 
0

是的,这是可能的。

首先获取div的宽度并添加6px。

var width = parseInt($("div").css("width").replace("px","")) + 6; 

然后使用nth选择器jQuery设置宽度。

$("div span:nth-child(2)").css("width", width); 
1

您可以用childrenwidth组合做到这一点:

var context = $("div"); 
(context.children("span")[2]).width(context.width() + 6); 
0

在这种fiddle该脚本将6像素到div的宽度和第二个孩子跨度。

$(document).ready(function() { 
    var wdth = $('div').width(); 
    wdth += 6; 
    $('div').css({ 
    'width': wdth 
    }); 
    $('div span:nth-child(2)').css({ 
    'width': wdth 
    }) 
}); 

在这样的例子有没有问题,选择的div没有class和id,但是如果你有更多的div,这将是比较复杂,选择一个你想要的 - 因此,我建议把一个类或身份证给它,你会在你的情况。