2016-05-13 51 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,這將是比較複雜,選擇一個你想要的 - 因此,我建議把一個類或身份證給它,你會在你的情況。