Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This works:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Test page&lt;/title&gt; &lt;script type="text/javascript"&gt; function func (img) { if(img.height &gt;= img.width) { img.style.height = "100%"; img.style.width = "auto"; } else { img.style.width = "100%"; img.style.height = "auto"; } } function rsz(imgname) { alert('resize '+imgname); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table width="80%" height="90%" cellpadding="0" cellspacing="5" border="1" style="margin-left:auto;margin-right:auto;"&gt; &lt;tr&gt; &lt;td width="50%" height="80%" onclick="alert('pic 1') " id="td1" style='text-align: center;'&gt; &lt;img id="imgL" onload="func(this);" src="http://img.yandex.net/i/www/logo.png" /&gt; &lt;/td&gt; &lt;td width="50%" height="80%" onclick="alert('pic 2') " id="td2" style='text-align: center;'&gt; &lt;img id="imgR" onload="func(this);" src="http://t2.gstatic.com/images?q=tbn:ANd9GcROiXx6BaNBDTn4xAS8FBMH7qUZIOPKcXZKL6asl4hHw2ys-h8Z" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>What I have done is remove the <code>&lt;center&gt;</code> tags and redo the centering with CSS, added a couple of closing <code>;</code> on the end of some JS lines, removed the <code>img.style.position = "relative"</code> as it was doing nothing in this context (you need to tell it <em>where</em> to be postioned) and moved the <code>&lt;script&gt;</code> element to the <code>&lt;head&gt;</code> - not necessary to make it work but makes it more readable.</p> <p>HOWEVER, what you are doing will not always produce the result you want because your table cells are not explicitly square. Becuase the shape of the cell is dictated by the shape/size of the browser window (due to the fact all sizes are stated in %) if you get an image that is <em>almost</em> square, but slightly taller than it is wide, and the browser is shaped in a tall manner, the image will overflow the vertical edges of the cell (try loading the above page and resizing and you will see Stan overflow out the right side of his container).</p> <p>If you insist on using a table to do this (should be using DIVs and CSS really) you need to add a calculation to account for the fact that your containers don't necessarily have an aspect ratio of 1:1 or, preferably, size them explicitly so you always know what their aspect ratio is.</p> <p><em>EDIT</em>: I have just changed the above example so you are passing the image itself to the function, rather than the ID of the image, which is more efficient since you no longer have to do a <code>document.getElementById</code> to obtain the reference.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload