iOS Safari中输入类型为范围的webkit-slider-thumb背景颜色无法改变?

3

在我的网站上实现input type range时,我遇到了一个问题。我尝试将-webkit-slider-thumb的背景颜色设置为透明,但在iOS设备(iPhone和iPad)的Safari浏览器上无法正常工作。 Safari检查器仍然显示用户代理样式,而不是我在css和内联html文件中实现的样式,以下是我在css文件和内联html中实现的样式:

HTML文件

<input class="slider" list="steplist" max="100" name="range" type="range" value ="0" />
input[type="range"]::-webkit-slider-thumb, 
input[type="range"]::-webkit-slider-thumb:active{
    background-color: transparent !important;
}

这是 iPad OS Safari 上检查元素的截图: enter image description here 我注意到当使用者代理默认样式时,输入范围的背景色input[type="range"]::-webkit-slider-thumb仍然是白色,而不是遵循我的透明CSS文件。

1
你的代码中没有包含任何类似于 input[type="range"]{-webkit-appearance: none} 的重置样式,如果没有这些样式,浏览器将会使用默认/代理输入样式。 - herrstrietzel
1个回答

5
根据我的分析,添加一些JS代码可以让您获得所需的输出。我已经成功实现了 -webkit-slider-thumb 的 background: transparent;,尽管我的方法需要使用一点JavaScript。在iOS上,效果非常完美;实际上,您在预览中看到的将是其他设备获得的效果。
iOS(Safari) 预览图: iPhone 14 | iPhone 14 Plus | iPhone 13 | iPhone 12 Mini 其他(Chrome) 预览图: Samsung Galaxy S22 | Pixel 7 Pro 这个例子帮助我找到了解决办法:https://codepen.io/tippingpointdev/pen/bGgLqLY

//Assign input range's id into variable
const range = document.querySelector('#r-input'); 

function rangeOnChange(e) {
  let t = e.target
  
  //Assign range input's properties into variables
  const min = t.min; 
  const max = t.max;  
  const val = t.value;  
  
  /* Adjust range progress as the thumb moves while avoiding overflows */
  t.style.backgroundSize = (val - min) * 89 / (max - min) + '% 100%'; 
}

//Trigger function on thumb move
range.addEventListener('input', rangeOnChange);

/* Adjust range progress at start */
range.style.backgroundSize = (range.value - range.min) * 89 / (range.max - range.min) + '% 100%';
input[type="range"] {
  
  /* To hide ordinary range input */
  -webkit-appearance: none;

  margin-right: 15px;
  height: 7px;
  background: lightgray;
  border-radius: 5px;
  
  /* Range progress background is set */
  background-image: linear-gradient(gray,gray);
  background-size: 70% 100%;
  background-repeat: no-repeat;
}

/* Thumb styles */
input[type="range"]::-webkit-slider-thumb {

  /* To hide ordinary thumb */
  -webkit-appearance: none;
  
  height: 15px;
  width: 15px;
  border-radius: 50%;
  
  /* Since range input is created manually, thumb background can be vary in color */
  background: transparent; 
  border: 1px solid gray;
  cursor: pointer;
  transition: background .3s ease-in-out;
}
<!-- Since some JS is used, an Id is added here -->
<input id='r-input' type="range" value="70" min="0" max="100" /><p><small>Try moving transparent thumb to see range progress</small></p>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接