带有自定义图像和文本的表单按钮

smo*_*ont 5 html css image button

表单按钮具有170x60图像,用于非按下和按下状态.我似乎无法做到的是按钮中的文本.我真的想避免编辑图像并直接将文本写入其中.现在我正在使用:

<input type="image" src="img/button_normal.png"
 width="175" height="60" onmousedown="this.src='img/button_pressed2.png'"
 onmouseup="this.src='img/button_normal.png'"> 
Run Code Online (Sandbox Code Playgroud)

我认为不可能在文本之上进行这项工作(据我所知).所以,我尝试使用,<button>但我无法让它工作.

我已经能够将文本放在上面的图像上,但是文本在哪里,按钮是不可点击的,这不起作用.

这个问题有什么解决方案?

Bal*_*usC 6

<input type="image">意味着有一种图像映射作为按钮.提交时,它会向服务器端发送一个name.xname.y参数,该参数表示客户端在图像映射上按下的确切位置.

你显然不想拥有它.您只想拥有一个带背景图片的按钮.为此,您通常使用CSS background-image属性(或更方便地使用background属性).

基本示例:

.mybutton {
    background-image: url('normal.png');
    width: 175px;
    height: 60px;
}
.mybutton.pressed {
    background-image: url('pressed.png');
}
Run Code Online (Sandbox Code Playgroud)

使用正常按钮如下:

<input 
    type="submit"
    class="mybutton" 
    value=""
    onmousedown="this.className+=' pressed'"
    onmouseup="this.className=this.className.replace(' pressed', '')"
>
Run Code Online (Sandbox Code Playgroud)

编辑:用于downvoters或JS/jQuery的nitpickers:IE LTE 7不会支持:hover也不:activepseudoselectors上的其他元素比a元件.以上解决方案是交叉浏览器兼容的.


Rei*_*ica 5

为什么不使用css和"提交"类型?

<input type="submit" class="myButton" value="Label goes here" />
Run Code Online (Sandbox Code Playgroud)

然后在你的CSS中:

input.myButton{
     background-image: url('img/button_normal.png');
     border-style:none;
}
input.myButton:hover{
    background-image: url('img/button_pressed2.png');
}
input.myButton:active{
    background-image: url('img/button_normal.png');
}
Run Code Online (Sandbox Code Playgroud)

这也适用于"按钮"类型,并且优于Javascript版本,因为不必启用Javascript.

为了在IE中正常工作,您可以使用此脚本使IE表现自己:)


Ina*_*thi 2

那么为什么不在常规按钮上编辑背景图像呢?

<script type="text/javascript" src="picker/js/jquery.js"></script>
<!-- some time later -->
<input type="button" src="img/button_normal.png" 
width="175" height="60" value="Some Text"
onmousedown="$(this).css({'background-image': 'img/button_pressed2.png'});" 
onmouseup="$(this).css({'background-image': 'img/button_normal.png'});"> 
Run Code Online (Sandbox Code Playgroud)

这应该使您能够将图像放入按钮中并覆盖一些文本。