简体   繁体   English

如何获得动态创建的元素宽度并对其应用样式?

[英]how to get dynamically created elements width and apply style to that?

I am creating an li element dynamically like this: 我正在动态创建一个li元素,如下所示:

$(data).find('slide').each(function(numSlide){
  var slideLink = $(this).attr('link');
  var slideimage = $(this).children('slideimage').text();
  var slidedesc = $(this).children('slidedesc').text();

  $('.slider ul').append('<li><a href="'+slideLink+'"><img src="'+root+"images/top-slider-image/"+slideimage+'" alt="welcome to Burger Davis Blog" /></a><div class="note">'+slidedesc+'</div></li>');
})

But I'd like to calculate the width of the li , and I need to apply some style to it -- how can I do that? 但是我想计算li的宽度,我需要对其应用一些样式-我该怎么做? If I add styles via the css method, it does not work for dynamically created elements... 如果我通过css方法添加样式,则不适用于动态创建的元素...

Please help me to get dynamic elements' width and how to apply styles into that? 请帮助我获得动态元素的宽度以及如何在其中应用样式?

I know we can use the live function, but I can't get even by that.. 我知道我们可以使用live功能,但是我什至无法使用。

$(data).find('slide').each(function(numSlide){
  var slideLink = $(this).attr('link');
  var slideimage = $(this).children('slideimage').text();
  var slidedesc = $(this).children('slidedesc').text();
  var li = $('<li><a href="'+slideLink+'"><img src="'+root+"images/top-slider-image/"+slideimage+'" alt="welcome to Burger Davis Blog" /></a><div class="note">'+slidedesc+'</div></li>');
  $('.slider ul').append(li);
  var w = li.outerWidth();
  li.css('width', w + 100);
})

This is a contrived sample. 这是人为的示例。 create the link outside the append so you can access it directly and utilize either innerWidth() or outerWidth() to get the width value. 在附录外部创建链接,以便您可以直接访问它,并利用innerWidth()或externalWidth()来获取宽度值。 Then just reference the css function of the item you create. 然后,只需引用您创建的项目的CSS函数即可。 In this example I just take the current width and add 100 to it. 在此示例中,我只是采用当前宽度并将其加100。

将元素添加到DOM后,其宽度为

element.offsetWidth

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

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