简体   繁体   English

Rails 3 / Javascript-设置div的宽度

[英]Rails 3 / Javascript- Set width of div

I hate to ask the same question that's on here several times but I'm struggling to bring it all together. 我不愿意多次提出相同的问题,但我一直在努力将所有问题整合在一起。

I'm doing something I think should be pretty simple with javascript. 我正在做一些我认为使用javascript很简单的事情。 Each time a page loads, I need to find with width of an img. 每次加载页面时,我都需要查找img的宽度。 With that img width, I need to assign it to the width of the div. 使用该img宽度,我需要将其分配给div的宽度。 So far I've come up with: 到目前为止,我已经提出了:

$(window).load(function() {
  var imgWidth = $("img").width();
  $function setWidth(imgWidth){
    $("#main").css("width":imgWidth);
    return false;
  });
});

For each page that loads, I want to assign with width of the img (only one on a page) to my imgWidth variable. 对于每个加载的页面,我想为imgWidth变量分配img的宽度(页面上仅一个)。 I then pass that variable into a function to change the css of my div with an id of mmain to with imgWidth. 然后,我将该变量传递给函数,以将ID为mmain的div的css更改为imgWidth。

Basically, I'm stuck. 基本上,我被卡住了。 I can't get anything to work and am having problems seeing why I can't get it to resize. 我什么都无法工作,并且在查看为何无法调整大小时遇到​​问题。

Anyway, appreciate the help. 无论如何,感谢您的帮助。 I'm on rails 3, using jquery. 我在使用jQuery的3。

Using jQuery it's 使用jQuery的

$(document).ready(function() {
  $("#main").width($("img").first().width());
});

Here were your mistakes: 这是您的错误:

  • You should call document ready 您应该准备好致电文件

  • $("img") retrieves an array of elements. $("img")检索元素数组。 So either take the first like I did or provide a precise matcher. 因此,要么像我一样先做一个,要么提供一个精确的匹配器。

  • You're badly defining a function you don't call 您定义的函数不正确

  • You're badly passing value to css attribute: Doc here . 您很难将值传递给css属性: Doc here

I think you just need to change 我想你只需要改变

$("#main").css("width":imgWidth);

to

$("#main").css("width",imgWidth);

docs docs

Have you considered just floating the div? 您是否考虑过将div浮动? Eg 例如

div#picture {
float: left; 
}

This way the width of the div will adapt to the size of the image - no JS required. 这样div的宽度将适应图像的大小-不需要JS。

HTH 高温超导

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM