如何使用主题创建Javascript按钮?

时间:2011-11-17 14:40:26

标签: javascript html css

我有一个附加到js动作的按钮。它目前使用<a onMouseUp="..."><img...。问题是我希望按钮能够根据主题(即css文件)更改图像。由于图像是在html本身中指定的,因此不起作用。有谁知道如何实现这个?

3 个答案:

答案 0 :(得分:2)

不应在HTML中包含图像,而应将其指定为锚元素的背景,如样式表中所定义。

a.example {
     display:inline-block;
     height:20px;
     width:20px;
     background-image:url(/images/buttonExample.png)
}

答案 1 :(得分:1)

这很简单(假设我理解你的问题):

a)为您想要的状态创建图像:    a.1 - 标准显示;    a.2 - 鼠标悬停; (徘徊)    a.3 - 鼠标按下; (有源)

b)在css中定义许多不同的按钮:

b.1 - themeCities

     .tcButton { width:100px; height:24px;
            background-image: transparent url(theurl) no-repeat top left; }
     .tcButton:hover {
            background-image: transparent url(thehoverurl) no-repeat top lef; }
     .tcButton:active {
            background-image: transparent url(theactiveurl) no-repeat top left; }

b.2 - themeNature

     .tnButton { width:100px; height:24px;
            background-image: transparent url(theurl) no-repeat top left; }
     .tnButton:hover {
            background-image: transparent url(thehoverurl) no-repeat top lef; }
     .tnButton:active {
            background-image: transparent url(theactiveurl) no-repeat top left; }

等等。第四。

你应该考虑精灵,否则你将会得到无法管理的大量图像。另一个考虑因素是按钮的大小:宽度和高度。

我可以帮助精灵,......如果需要的话。有免费网站可以为您管理。我是一个控制狂,并且在创建精灵图像时使用Adobe Fireworks来满足我所有的精灵需求。

然后,考虑到图像或精灵,您可能想要使用css-ninja建议如何加速图像预加载:

.body:after {
    content: url(image-url-1) url(image-url-2) url(image-url-n);
    display:none;
}         

创造精灵的伎俩:

a)确保背景是透明的,并将它们保存为gif或png32;

b)确保三种状态的尺寸相同,否则您将有抖动显示;

c)完成所有图像后,将它们组装成一个大的透明背景图像;

d)将它们放在新的大透明图像中;将它们左右对齐;

e)在每张图片之间留出一些空间。有人建议图像之间并排和自上而下50像素。我不遵循这一点。我只是在它们之间留出一些空间。

f)硬编码精灵中最困难的任务:在大透明图像中记下它的坐标:顶部,左侧,宽度,高度。

要使用精灵图像,您可以这样(作为众多变体之一):

 .msSprites { background: transparent url(url-of-the-sprite-image.gif) no-repeat;
     top left; } /* msSprites = my site sprites */
 .tcButton  { background-position: 0 0; width:100px; height: 24px; }
 .tcButtonHover { background-position: 0 -150px; width:100px; height: 24px; }
     /* margin-left at 0px; margin-top:150px ... in the large transparent image */
 .tcButtonActive { background-positon: 0 -300px; width:100px; height: 24px; }
     /* margin-left at 0px; margin-top:150px ... in the large transparent image */

 .tnButton { background-position: -150px 0; width:100px; height:24px; }
     /* margin-left at 150px; margin-top at 0 px .. in the large transparent image */
     ... and so fourth

应用:

常规图片:

<button class='tcButton' onClick ....>This is fun</button>

精灵:

<button class='msSprites tcButton' onClick ...>This is even more fun</button>

在这种情况下,精灵由大透明图像和您想要使用的按钮的位置组成。

我希望我真的很困惑你......或者打开你的思维帽。

祝你好运!

答案 2 :(得分:0)

如果您使用的是jQuery,则可以更改图像标记源属性。

<a href="#" onclick="changeButton()"><img src="oldImageSrc.jpg" /></a>

然后在javascript方法中:

function changeButton() {
   $("img", this).attr("src", "newImageSrc.jpg");
}