2016-04-12 56 views
0

突然我的代码停止工作,问题是我想输出范围值到范围的拇指。输入类型范围 - 拇指错误输出

这里是我的代码:

<input id="slider1" type="range" min="5000" max="350000" step="1000" value="5000" name="beloeb" oninput="outputUpdate(value)" /> 

JS:

function outputUpdate(vol) { 
function formatNumber (num) { 
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.") 
} 
document.styleSheets[0].addRule('#slider1::-webkit-slider-thumb::before','content: "'+formatNumber(vol)+' DKK";'); 
} 

这在控制台中使用铬时出现错误:

未捕获的语法错误:未能执行上“的CSSStyleSheet 'addRule' ':解析规则失败'#slider1 :: - webkit-slider-thumb :: before {content:“8.000 DKK”; }”。

回答

0

::-webkit-slider-thumbnot a standard pseudo selector

此功能是非标准的,而不是一个标准的轨道。不要在面向Web的生产站点上使用它:它不适用于每个用户。实现之间也可能存在很大的不兼容性,并且行为在未来可能会发生变化。

如果你在CSS验证检查你的代码,你会碰到这样的:

::-webkit-slider-thumb is an unknown vendor extended pseudo-element

所以可能是浏览器的新版本支持停止的财产。

现在还没有一种标准的方法来实现CSS。但也有使用的div实现同样的结果一些很好的工具/跨越像http://refreshless.com/nouislider/

+0

是否有任何其他方式向值添加到范围拇指? –

+0

@PatrickLarsen我没有看到任何标准的跨浏览器支持的方式来做到这一点很容易。你可以查看这篇文章https://css-tricks.com/styling-cross-browser-compatible-range-inputs-css/,但不是一个很好的支持功能。 –

0

正如Avraam's response指出的那样,::webkit-slider-thumb风格是不规范的,不会在任何形式的跨浏览器的感工作。结果styleSheet.addRule()函数将无法解析它。

你可以考虑使用Javascript,如果不已经在当前页面存在,而不是直接将它添加到样式表创建一个<style>块包含你的目标风格:

<script> 
    function outputUpdate(vol) { 
    // Create a style block 
    var style = document.createElement('style'); 
    // Set an ID for style and type 
    style.id = 'slider-rule'; 
    style.type = 'text/css'; 
    // If the style doesn't exist in the DOM... 
    if(!document.getElementById(style.id)){ 
     // Resolve the head section of the document 
     var head = document.head || document.getElementsByTagName('head')[0]; 
     // Style content 
     var content = '#slider1::-webkit-slider-thumb::before{ content: "'+formatNumber(vol)+' DKK";}'; 
     if (style.styleSheet){ 
      style.styleSheet.cssText = content; 
     } else { 
      style.appendChild(document.createTextNode(content)); 
     } 
     // Append this tag to the <head> section 
     head.appendChild(style); 
    } 
    } 

    function formatNumber (num) { 
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.") 
    } 
</script> 

这显然不能解决跨浏览器的关注,但它会适当<style>块添加到DOM,如果不存在的话:

enter image description here