简体   繁体   English

如何从样式表中删除:hover CSS规则

[英]How to remove :hover css rule from stylesheet

I am working on a project based on jQuery and javascript. 我正在基于jQuery和javascript的项目中。 I am trying to add the CSS rules using javascript insert/addRule properties. 我正在尝试使用javascript insert / addRule属性添加CSS规则。 What I want to do is : 我想做的是:

I have to create hover effect and insert them into the stylesheet using javascript css properties. 我必须创建悬停效果,然后使用javascript css属性将它们插入样式表。 For this I am creating two classes for example: 为此,我将创建两个类,例如:

.dummy {.... }

and

.dummy:hover{.....}

I want that If I change the hover effect then it must delete the previous one (or duplicates ) from the stylesheet and insert the new rules to the stylesheet. 我希望如果我更改悬停效果,那么它必须从样式表中删除前一个(或重复项)并将新规则插入样式表。

But the problem is that If I try to remove or delete the CSS rules using deleteRule or removeRule it removes only 但是问题是,如果我尝试使用deleteRule或removeRule删除或删除CSS规则,它只会删除

.dummy{...} rule but not the .dummy:hover{...} .dummy{...}规则,但不包括.dummy:hover{...}

Here is my code that can help you to understand what I am doing: 这是我的代码,可以帮助您了解我在做什么:

function createNewStyle() {
    var style = document.createElement("style");
    style.setAttribute('id', 'd-set-stylesheet');
    style.appendChild(document.createTextNode(""));
    document.head.appendChild(style);
} // this function might be not required but included here so that you may understand the program flow.

//the main issue is with this function.
function removeIfExists(class_name) {
    var styleTag = document.getElementById("d-set-stylesheet");
    var styleRef = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet;
    if (styleRef.rules) { //all browsers except IE 9-
        console.log(styleRef);
        for (var i in styleRef.cssRules) {
            if (styleRef.cssRules[i].selectorText === "." + class_name+":hover" ||styleRef.cssRules[i].selectorText === "." + class_name )
                styleRef.deleteRule(i);
        }
    } else {
        var i;
        for (i = 0; i < styleRef.rules.length; i++) {
            //if(styleRef.rules[i].selectorText === "."+class_name || styleRef.rules[i].selectorText === "."+class_name+":hover")
            styleRef.removeRule(i);
        }
    }
    return styleRef;
}

 //this function maybe not related with the issue but if it is you can check it.
function setNewClass(element, class_name, classSelector, styleObject) {
    var stylesheet = removeIfExists(class_name);
    if (element.data('hover-class') == null)
        element.data('hover-class', class_name);
    let count = 0;
    var style = [];
    var property = [{
        "append": ":hover"
    }, {
        "append": ""
    }];
    for (j = 0; j < 2; j++) {
        style.push({});
        style[j].sheet = stylesheet;
        style[j].selector = class_name;
        style[j].type = classSelector;
        style[j].property = property[j]["append"];
        style[j].style = "";
    }
    for (i in styleObject) {
        if (styleObject.hasOwnProperty(i))
            if (count % 2 == 0)
                style[0].style += styleObject[i] + ":";
            else
                style[0].style += styleObject[i] + ";";
        count++;
    }
    style[1].style = "transition:" + styleObject.t_property_value;
    addCSSRule(style);
}

function addCSSRule(styleSheet) {
    console.log(styleSheet);
    for (i = 0; i < styleSheet.length; i++)
        if (styleSheet[i].sheet.insertRule)
            styleSheet[i].sheet.insertRule(styleSheet[i].type + styleSheet[i].selector + styleSheet[i].property + "{" + styleSheet[i].style + "}", styleSheet[i].sheet.cssRules.length);
        else
            styleSheet[i].sheet.addRule(styleSheet[i].type + styleSheet[i].selector + styleSheet[i].property, styleSheet[i].sheet.style, -1);
}

Here are the images that of console.log In the first image the hover and without hover class is added to CSS rules. 这是console.log的图像,在第一个图像中,将没有悬停类的悬停添加到CSS规则中。 图像优先:删除规则之前,仅插入规则

In the second image the previous hover class is not deleted while without hover class is deleted. 在第二个图像中,先前的悬停类别未删除,而没有悬停类别则删除。 I want hover transition must be deleted. 我希望悬停过渡必须删除。 Before adding new Rules to prevent duplication of classes and more than one transition on hovering the element should be prevented. 在添加新规则以防止类重复和在将元素悬停时进行多个过渡之前,应避免。 图像秒:删除规则后,悬停效果不会消失

Thank you. 谢谢。

I found the answer today. 我今天找到了答案。 I will explain it so that it can help others in future to understand the problem and solution. 我将对其进行解释,以便将来可以帮助其他人了解问题和解决方案。

As through my question, you can understand the issue. 通过我的问题,您可以理解问题。 The problem was with this function only 问题仅在于此功能

function removeIfExists(class_name) {
 ......
if (styleRef.rules) { //all browsers except IE 9-
    for (var i in styleRef.cssRules) {
           .....
            styleRef.deleteRule(i); //problem is with this.
           .....
    }
   }
  .......
   return styleRef;
}

When I check the deleteRule on the basis of some test I found that when the deleteRule is called following things happens: 当我根据一些测试检查deleteRule时,我发现调用deleteRule时会发生以下情况:

  1. The css rule is deleted on the basis of index. 将根据索引删除css规则。
  2. (The most important, as there is no documentation or clarification or explanation about this) The content get updated with their indexing. (最重要的是,因为没有相关的文档,说明或说明)内容会随着索引编制而更新。 So that my function will no longer be able to delete the correct rules on the basis of old indexing. 这样我的函数将不再能够基于旧索引删除正确的规则。

To understand it better I will give you an example: 为了更好地理解它,我将举一个例子:

Suppose, I have added two rules in css such as: .dummy:hover{...} and .dummy{...} 假设我在CSS中添加了两个规则,例如: .dummy:hover{...}.dummy{...}

Now the indexing of these rules will be as follows: 现在这些规则的索引如下:

[0]: .dummy:hover rule
[1]: .dummy rule

When i call the delete rule what happen is : 当我调用删除规则时,会发生以下情况:

// at i =0; 
deleteRule(0);/* will be called and it will remove [0]: .dummy:hover rule
 and then it will update the rules indexing again, which means
 [1]: .dummy rule => [0]: .dummy rule */
// now when i = 1;
deleteRule(1); /* will be called and it will try to remove [1]: .dummy rule which is not here anymore and it will just skip the removal of [1]: .dummy rule.

So what I do to remove it is starting to remove the rule from highest indexing or in reverse order which means the i = 1 rule will be deleted first then i=0; 因此,我要删除的操作是开始从最高索引中删除规则或以相反的顺序删除规则,这意味着先删除i = 1规则,然后再删除i = 0; rule so that there would not be any consequences. 裁定不会有任何后果。

and the function would changed as this: 并且函数将更改为:

function removeIfExists(class_name)
{
    ...
    var styleRef = styleTag.sheet ? styleTag.sheet : styleTag.styleSheet;
    var len = styleRef.cssRules ? styleRef.cssRules.length : styleRef.rules.length;
    if(styleRef.rules){ //all browsers except IE 9-
        for(i=len;i>0;i--)
        {
                if (styleRef.cssRules[i-1].selectorText === "." + class_name+":hover" ||styleRef.cssRules[i-1].selectorText === "." + class_name )
                styleRef.deleteRule(i-1);
        }
    }
    ......
    .....
    }
    return styleRef;    
}

Note : The similar procedure would be followed for IE but I have not included it here. 注意:对于IE,将遵循类似的过程,但此处未包括在内。

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

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