2017-05-10 14 views
0

これは基本的なようだが、私はその周りを頭で囲むことができない.Honestは手がかりを得ていないが、 cssファイルのようなものですが、今回はiwnaがその方法や手法を知っています。イメージの幅を元の幅であるがパーセンテージで設定するためのJavaScriptの公式

例..

//I have tried this but it didn't work 
 
//var image_width_from_server=(the_img_width_from_php); 
 

 
//image_width_from_server=image_width_from_server/$(parent).width()*90 
 

 

 
//Now the result i get from the console does not match the browser set width of the image's p-ercentage width.
#parent{ 
 
width:250px; 
 
height:250px; 
 
background:deepskyblue; 
 
border:5px; 
 
} 
 

 
#parent img{ 
 
width:90%;/**Now how can i do this in javaScript..?*/ 
 
height:auto; 
 
} 
 

 

 
/**Please note that direct css code won't help. 
 
I need a way in javaScript to set the image's width using percentage but also basing on both the image's width size and the parent width size too. 
 
*/
<div id='parent'> 
 
    <img src='https://i.vimeocdn.com/video/584087165_780x439.jpg'/> 
 
</div>

直接CSSコードは助けにはなりませんのでご注意ください。 イメージの幅をパーセンテージで設定するにはjavaScriptでの方法が必要ですが、イメージの幅のサイズと親の幅のサイズの両方にも基づいています。

実際には考えられていません。

ありがとうございます。

答えて

1

最初に画像を選択してから、jsから幅を設定できます。

$('#parent > img').css('width', '90%'); 
2

新しい幅=(古い幅/ 100)*パーセンタイル?その後、

1

あなたは要素の幅を取得するために.offsetWidthを使用することができます代わりにjQueryののJavaScriptのバニラを使用する場合、および:計算を使用して回避

var newWidth=document.getElementById("parent").offsetWidth * 0.9; // Get 90% of parent width 

document.getElementById("img").style.width = newWidth + "px"; // Set the new width 

別の簡単な解決策は、直接幅の割合を設定することで構成されています(まだバニラJavaScriptを使用)

document.getElementById("img").style.width = "90%"; 
+0

この計算は必要ありません。あなたは画像にパーセンテージの幅を適用することができます。 – kotapeter

+0

本当に 'document.getElementById(" img ")。style.width =" 90% "'を実行するだけでいいですが、要素の幅を取得する方法を示すのは便利だと思いました。この問題に取り組むには複数の方法があります。 –

関連する問題