简体   繁体   English

将CSS宽度和高度添加到jQuery图像元素

[英]Adding css width and height to jquery image element

I am trying to add css of width and height to this line of jquery. 我试图将宽度和高度的css添加到这行的jQuery。 I want my image to have width 160 and height 80. Will some one please tell me what I am doing wrong. 我希望图像的宽度为160,高度为80。请告诉我我做错了什么。

This is the line of code creating my image: 这是创建我的图像的代码行:

$("#selectedSpecialtyPlateImage").html("<img src='"+selectedLicense.image+"' alt='"+selectedLicense.code+"' />");

What I have Tried: 我尝试过的

$("#selectedSpecialtyPlateImage").html("<img src='"+selectedLicense.image+"' alt='"+selectedLicense.code+"' />").width(160).height(80);

(This is doing the div but not the image inside the div) (这是在做div,而不是div内的图片)

or 要么

$("#selectedSpecialtyPlateImage").html("<img style="width: 160px; height: 80px;" src='"+selectedLicense.image+"' alt='"+selectedLicense.code+"' />");

I was thinking this would add the style to the image but instead is just breaking my code completely. 我当时以为这会增加图像的样式,但是却完全破坏了我的代码。

Any help with this would be greatly appreciated! 任何帮助,将不胜感激!

First example is wrong, because you are setting width to element, not to image. 第一个示例是错误的,因为您是将宽度设置为元素,而不是图像。 Second example is good, but you are using bad quotation marks. 第二个例子很好,但是您使用了错误的引号。

Change this: 更改此:

style="width: 160px; height: 80px;"

To this: 对此:

style='width: 160px; height: 80px;'

I think that best way to add image dynamicaly is this: 我认为动态添加图像的最佳方法是:

var img = $('<img />', {
  src: selectedLicense.image,
  alt: selectedLicense.code
});
img.appendTo($('#selectedSpecialtyPlateImage'));

If you need to set the style attributes, you can use jQuery's .css() 如果需要设置样式属性,则可以使用jQuery的.css()

What do you think about this solution? 您如何看待该解决方案?

$('div.content img').css({
  'width' : '100px',
  'height' : '100px'
});

Although I am not fan of jQuery, and I really do not prefer to set html elements as string, below snippet should work. 尽管我不是jQuery的粉丝,并且我确实不喜欢将html元素设置为字符串,但是下面的代码片段应该可以工作。

$("#selectedSpecialtyPlateImage")
  .html('<img style="width: 160px; height: 80px;" src=' +selectedLicense.image+' alt='+selectedLicense.code +' />');

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

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