引用下面的截图,我创建了一个div
来包裹另外两个div
图像和文本,然后我使用CSS position:absolute
使这些 div
合并在一起。
但是,我在移动设备上测试时发现按钮不灵敏,有时需要按几次按钮才能生效。
那么,我的代码有问题吗?创建包含图像和文本的按钮的最佳实践是什么?
谢谢
<div class="r">
<div class="a">
<div class="i"><img src="store_btn_on.png" /></div>
<div class="t">Shatin</div>
</div>
<div class="b">
<div class="i"><img src="store_btn_off.png" /></div>
<div class="t">Causeway Bay</div>
</div>
<div class="c">
<div class="i"><img src="store_btn_off.png" /></div>
<div class="t">Kowloon Bay</div>
</div>
</div>
javascript部分更新
addButtonListener($("#store > .r > .a"), function(event, target){
$("#some_content").css("display", "none");
$("#other_content").css("display", "block");
$(".r > .b > .a > img").attr("src" , "store_btn_on.png");
$(".r > .b > .b > img, .r > .b > .c > img").attr("src" , "store_btn_off.png");
});
function addButtonListener(targets, job){
if ("ontouchstart" in document.documentElement){
targets.each(function(){
$(this)[0].addEventListener('touchstart', function(event){
event.preventDefault();
$(this).attr({ "x": event.targetTouches[0].clientX, "diffX": 0, "y": event.targetTouches[0].clientY, "diffY": 0 });
$(this).addClass("on");
}, false);
$(this)[0].addEventListener('touchmove', function(event){
$(this).attr({
"diffX": Math.abs(event.targetTouches[0].clientX - $(this).attr("x")),
"diffY": Math.abs(event.targetTouches[0].clientY - $(this).attr("y"))
});
}, false);
$(this)[0].addEventListener("touchend", function(event){
$(this).removeClass("on");
if ($(this).attr("diffX") < 5 && $(this).attr("diffY") < 5){ $(job(event, $(this))); }
}, false);
});
}
else {
targets.each(function(){
$(this).mousedown(function(event){ event.preventDefault(); $(this).addClass("on"); });
$(this).mouseup(function(event){ event.preventDefault(); if ($(this).hasClass("on")){ $(job(event, $(this))); } $(this).removeClass("on"); });
$(this).hover(function(event){ $(this).removeClass("on"); });
});
}
}
最佳答案
我不确定您的按钮在移动设备上的敏感性(您没有显示任何用于处理点击事件的代码),但我认为最好像这样编写 HTML:
<div class="r">
<div class="button on">
<span>Shatin</span>
</div>
<div class="button">
<span>Bay</span>
</div>
<div class="button">
<span>Bay</span>
</div>
</div>
然后在样式表中使用 CSS:
.button {
background: url(http://domain.com/images/store_btn_off.png) no-repeat 0 0;
/* Additional button styles */
}
.button.on {
background: url(http://domain.com/images/store_btn_on.png) no-repeat 0 0;
}
.button span {
color: #FFF;
margin: auto;
}
这使得只需添加或删除 on 类即可轻松动态打开或关闭按钮。
虽然没有必要,但您可能也有兴趣查看 CSS3 渐变来创建类似的简单渐变背景图像,然后在没有任何渐变支持的浏览器中很好地降级为图像。
类名“r”和“b”不太具有描述性。除非某些 HTML/CSS 缩小器将它们放在那里并且您在开发代码中拥有正确的名称,否则我会考虑为您的类提供更具描述性的名称。
关于javascript - 移动网站中带有图像和文本的按钮的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10859484/