通过设置更大尺寸的背景图像突出显示img标记

时间:2022-12-10 22:42:53

I have two images one is textbox.png of size 16X16px and the other one is IconBG.png with 24X24 pixel. I am defining a img tag as

我有两个图像,一个是textbox.png,大小为16X16px,另一个是IconBG.png,大小为24X24像素。我正在定义一个img标签

<img id="g_TextButton"  src="../icons/textbox.png" alt="Text" title="Text" onclick="javascript:void(selectTool(this, 5))">

On click of this ,I am setting the background img for the img tag as below-

点击此处,我​​正在为img标签设置背景img,如下所示 -

function selectTool(objThis) {
    //----some code
    objThis.style.backgroundImage="url('../icons/IconBG.png')";


}

But as the img tag size is not predefined ,it will occupy 16px initially .After selection when I set the background image of 24 px, the size is still 16px .I cannot initialize the img tag size as 24px bz,with this even the 16px icon is reset to 24px.

但由于img标签大小没有预定义,它最初将占用16px。选择后我设置24像素的背景图像,大小仍然是16px。我不能将img标签大小初始化为24px bz,这甚至是16px图标重置为24px。

So my requirement is have a place holder with size 24X24.And initially place a img of 16X16 in it. Onclick add the background image of 24X24px.

所以我的要求是有一个24X24尺寸的占位符。最初放入一个16X16的img。 Onclick添加24X24px的背景图片。

Kindly help.

1 个解决方案

#1


3  

So you can achieve this easily with css only :

因此,您只需使用css即可轻松实现此目的:

HTML:

<div id="container">
    <img src="../icons/textbox.png" />
</div>

CSS :

#container {
    height: 24px;
    width: 24px;
    position: relative;
}

#container:hover {
    background-image: url('../icons/IconBG.png');
}

#container img {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

And the good thing is, the :hover will load the second img (img24px) onload and not on first call like it would happen by default in JS.

好消息是,:hover将加载第二个img(img24px)onload而不是第一次调用,就像在JS中默认情况一样。

#1


3  

So you can achieve this easily with css only :

因此,您只需使用css即可轻松实现此目的:

HTML:

<div id="container">
    <img src="../icons/textbox.png" />
</div>

CSS :

#container {
    height: 24px;
    width: 24px;
    position: relative;
}

#container:hover {
    background-image: url('../icons/IconBG.png');
}

#container img {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

And the good thing is, the :hover will load the second img (img24px) onload and not on first call like it would happen by default in JS.

好消息是,:hover将加载第二个img(img24px)onload而不是第一次调用,就像在JS中默认情况一样。