使用JavaScript将图像的高度和宽度设置为100% [英] Set Height and Width of an image to 100% using JavaScript

查看:74
本文介绍了使用JavaScript将图像的高度和宽度设置为100%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个单元格表格中有一个图像元素,当我单击按钮时,我想将图像元素的高度和宽度设置为表格单元格的大小.

表格单元格是由用户定义的,我们不知道该单元格的尺寸.我知道如果我们将图像的高度和宽度设置为100%,它将捕获图像或将其自身调整为其父对象的确切尺寸(在本例中为单元格).所以这是我用来将图像大小更改为100%的代码.

I have an image element in a single celled table, when i click on a button i want to set the height and width of the image element to the size of the table cell.

The table cell is defined by user and we do not know the dimensions of the cell. I know if we set the height and width of an image to 100% it grabs or adjusts itself to the exact dimension of its parent (which is the cell in this case). So here is the code i am using to change the image size to 100%.

<td class="image">
<img alt="" class="CustomImage"  önerror="this.src='/Image1.bmp'" src="/Image2.bmp" 

         style="position: inherit; top: 0px; left: 50%; height: 50%; width: 50%;" /></td>





function onClick()
{
iterating through some objects
if(node.className=="Image")
{
//the 0th node is the image element
node.childNodes[0].width = 100+"%"; 
node.childNodes[0].height = 100+"%";//here is where the code is failing and below are various ways i tried to solve
}
}





//various ways
var x = 100;
var size = x.toString()+"%";

var size = "100%"

var size = 100+"%";
var newsize = size.valueof();
var newsize1 = parseInt(size, 10);



不管我做什么,我定义的大小都是带引号的"100%".在运行时,高度为(height = 50%),不带引号.但是,当我把高度放到它的高度上时,它用引号引起来(高度="100%"),所以它不起作用.

我该如何实现?如何删除引号并为高度指定100%?


提示/其他信息:
函数.toString()将100转换为"100"
是否有任何东西可以将"100%"转换为100%



no matter whatever i do, the size i am defining is "100%" with quotes. In runtime the height is (height = 50%) without quotes. But when i put the height, its taking (height = "100%") with quotes, so its not working.

How do i achieve this? how do i remove the quotes and assign 100% to the height?


Hint/Extra Information:
the function .toString() converts 100 to "100"
is there anything that converts "100%" to 100%

推荐答案

function onClick()
{
   //iterating through some objects
   if(node.className=="Image")
   {
      //the 0th node is the image element
      node.childNodes[0].width = node.clientHeight; 
      node.childNodes[0].height = node.clientWidth;//this is the only solution i see as of now
   }
}


您是否尝试过使用"100%"或100 +%"?
Have you tried using ''100%'' or 100 +''%''?


如果您知道像素高度,那么您也可以使用
If you know the Pixel height , then you can also use
node.childNodes[0].width = "400px"// Your Pixel or you can it's parent element's Height in pixel and set to it.


这篇关于使用JavaScript将图像的高度和宽度设置为100%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆