繁体   English   中英

当用户点击HTML元素时,如何更改HTML元素的颜色?

[英]How do I change the color of a HTML element, when user taps on it?

我的问题很简单,我无法相信iOS 4及更高版本没有基于HTML / CSS的解决方案。

我有图像网格,每个图像都有一行灰色文字。 文本以顶部和底部的线条为界。

当用户轻击元素(图像或字幕)时,文本和线条应该将颜色更改为白色,并在他再次抬起手指时重置颜色。 如果在图像顶部出现一条额外的线条,我甚至会更好。 整个元素封装在div

我已经尝试在div或各种子元素上使用CSS属性-webkit-tap-highlight-color-webkit-active-link:hover:active ,但到目前为止没有任何成功。

正如建议我尝试这个文件

<!DOCTYPE HTML>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="highlight.css" />
    <style type="text/css"></style>
    <script type="text/javascript">
      div = document.getElementById('element');
      div.ontouchstart = function(){this.style.backgroundColor = '#fff';} // on tapping
      div.ontouchend = function(){this.style.backgroundColor = '#000';} // on releasing
    </script>
   <title></title>
  </head>
  <body>
    <div id="element">
      <p>Dies ist noch ein Test.</p>
      <p>Wenn man auf <a href="#">diesen etwas laengeren Link </a> tappt, sollte was     passieren.</p>
    </div>
  </body> 
</html>

用这个样式表

#element {
    width:200px;
    height:200px;
    border:solid;
    border-color:blue;
    -webkit-user-select:none;
}

但这似乎也行不通。

div = document.getElementById('#DIV');
div.onmousedown = function(){this.style.backgroundColor = ###;} // on tapping
div.onmouseup = function(){this.style.backgroundColor = ###;} // on releasing

既然你没有进入JS - 这里是你的完整脚本:

<script>
div = document.getElementById('elem');
div.onmousedown = function(){this.style.backgroundColor = '#f00';} // on tapping
div.onmouseup = function(){this.style.backgroundColor = '#000';} // on releasing
</script>

把它放在元素的标签之后。

这里有更好的东西:

<script>
function changeClr( id , clr ){
    document.getElementById( id ).backgroundColor = clr;
}
</script>

将上面的代码放在<head>元素中。 剩下要做的就是添加你的元素theese atts:

onmousedown='changeClr( "id" , "#f00" );' onmouseup='changeClr( "id" , "#000" );'

例如<div id='element' onmousedown='changeClr( "element" , "#f00" );' onmouseup='changeClr( "element" , "#000" );'></div> <div id='element' onmousedown='changeClr( "element" , "#f00" );' onmouseup='changeClr( "element" , "#000" );'></div>

该代码允许您通过添加theese atts来更改任何元素的颜色。

-webkit-tap-highlight-color就是当用户点击某些东西时发生的事情,它不是“开/关”状态。 您必须使用Javascript作为Michael备注来实现更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM