使用jQuery切换背景URL时如何保留-webkit-background-clip:text效果?
解决背景图切换后-webkit-background-clip:text失效的问题
问题出在你用jQuery设置整个background属性时,会把CSS里原本设置的background-clip、background-size等相关属性全部重置,导致文字裁剪效果丢失。
修复方案:只修改background-image属性
不要直接覆盖整个background,而是单独修改background-image,这样就能保留原本的background-clip、background-size等样式设置。
修改后的JS代码:
jQuery(function($) { var whatToSwitch = $('.homepage_overlaytext h1'); var backgrounds = ['url(http://static.jsbin.com/images/jsbin_static.png)', 'url(http://static.jsbin.com/images/popout.png)']; var current = 0; function nextBackground() { // 只修改background-image,而非整个background whatToSwitch.css( 'background-image', backgrounds[current = ++current % backgrounds.length] ); setTimeout(nextBackground, 5000); } setTimeout(nextBackground, 5000); whatToSwitch.css('background-image', backgrounds[0]); });
额外确认CSS设置
确保你的CSS属性没有被其他样式覆盖,保持如下设置即可:
h1 { background-size: contain; background-clip: text; -webkit-background-clip: text; color: transparent; -webkit-text-fill-color: transparent; }
这样切换背景图时,文字裁剪的效果就会保留下来——因为只有背景图的URL被替换,其他控制文字裁剪的background属性都没有被改动。
内容的提问来源于stack exchange,提问作者Kyle Hoogewerf
相关产品推荐
相关产品推荐

