jQuery/Javascript css(“width”) / check if style is defined in css?

后端 未结 4 681
慢半拍i
慢半拍i 2020-12-17 15:26

I have a stylesheet which defines default width for images. When I read the image width style with jQuery width() it returns the right width. It also returns th

4条回答
  •  鱼传尺愫
    2020-12-17 15:47

    I have a workaround idea that might work.

    Define a class named default_width before all other style sheets:

    .default_width { width: 1787px }  
    /* An arbitrary value unlikely to be an image's width, but not too large
       in case the browser reserves memory for it */
    

    to find out whether an image has a width set:

    • Clone it in jQuery: element = $("#img").clone()

    • give the cloned element the default_width class: element.addClass("default_width")

    • If its width is 1787px, it has no width set - or, of course, is natively 1787px wide, which is the only case in which this method will not work.

    I'm not entirely sure whether this will work, but it might. Edit: As @bobince points out in the comments, you will need to insert the element into the DOM for all classes to be applied correctly, in order to make a correct width calculation.

提交回复
热议问题