通过JS动态控制网站一键置灰

<el-button @click="handleChangeGray">一键置灰</el-button>

通过控制添加节点删除节点的方式达到一键置灰效果

/**控制一键置灰 */
handleChangeGray(){
    
    
    this.isGraying = !this.isGraying
    this.handleGraying(this.isGraying)
},
/**网页一键置灰 */
handleGraying(isGraying){
    
    
    if(isGraying){
    
    
        // 追加样式
        let garyStyle = document.createElement('style') 
        garyStyle.id = "htmlStyle"
        garyStyle.appendChild(document.createTextNode(
            `html{
                filter: grayscale(100%);
                -webkit-filter: grayscale(100%);
                -moz-filter: grayscale(100%);
                -ms-filter: grayscale(100%);
                -o-filter: grayscale(100%);
            }`
        )) 
       document.head.appendChild(garyStyle)
    }
    else{
    
    
        // 移除样式
        let htmlStyle = document.getElementById('htmlStyle')
        htmlStyle && htmlStyle.parentNode.removeChild(htmlStyle)
    }
}

ps:希望有更好的方法

猜你喜欢

转载自blog.csdn.net/qq_36687211/article/details/128873319