如何更改子节点事件上的父节点样式属性

How to change parentNode style attributes on childNode events

本文关键字:父节点 样式 属性 何更改 子节点 事件      更新时间:2023-09-26

嘿伙计们,我有一个这样的 UL:

<ul id="list">
    <li class="something">
        <div class="btns" onclick="add(this)"> + </div>
        <div class="btns" onclick="sub(this)"> - </div>
    </li>
    <li class="something new">
        <div class="btns" onclick="add(this)"> + </div>
        <div class="btns" onclick="sub(this)"> - </div>
    </li>
</ul>

CSS方面,类"something"包含一个背景图像。

我在这里想要实现的是,当进行 add() 或 sub() 函数调用时,进行调用的元素的 parentNode 的背景图像属性会发生变化......

所以这样,我就不必为每个元素制作 ID,并且可以重用相同的函数......

所拥有的是这样的东西,但它不起作用(相反,我编写的代码是错误的):

function add(x)
{
    var y = x.parentNode.style;
    if (y.backgroundImage == 'url("../assets/1.png")'
    {
        y.backgroundImage = 'url("../assets/2.png")';
    } else if (y.backgroundImage == 'url("../assets/2.png")'
        y.backgroundImage = 'url("../assets/3.png")';
    ...
    ... so on so forth...
}

整体逻辑本身可能很差,所以我也愿意接受新的建议......

编辑#1:添加了更多详细信息来解释当前情况...

本质上,有一个 3x3 网格填充了 li,背景图像使用点指示当前数量。每个 li 里面有两个按钮,用于加减。单击每个时,背景图像应该会更改为表示当前数量......这必须独立于不同的 li 来完成......

我同意 RobG 的观点,即使用类更适合 - 特别是如果您决定使用框架。在你不想的情况下,这里有一些其他方法:

针对计算样式进行了更新 - 将注释版本保留在帖子底部:这个的主要区别在于它获得内联样式或计算版本的背景图像(例如,如果它由类设置)。

要获取计算样式,请查看 quirksmode.org。在获取样式页面的底部部分。

这是一个在 jsfiddle 中不起作用的小提琴(有点累,但我认为这与我在工作中使用 IE6 有关......),但如果您在正常设置中在本地执行此操作,则可以正常工作。

function add(x) {
    var parent = x.parentNode;
    var y = parent.currentStyle['backgroundImage'] || document.defaultView.getComputedStyle(parent,null).getPropertyValue('backgroundImage');
    switch(true)
    {
        case (y.indexOf("1.png")!=-1):
            parent.style.backgroundImage = 'url("http://www.wskidmore.com/2.png")';
            break;
        case (y.indexOf("2.png")!=-1):
            parent.style.backgroundImage = 'url("http://www.wskidmore.com/3.png")';
            break;
        case (y.indexOf("3.png")!=-1):
            parent.style.backgroundImage = 'url("http://www.wskidmore.com/1.png")';
            break;
    }
} 

过时了,但有逻辑地评论了。

function add(x) {
        var y = x.parentNode.style.backgroundImage;
    // using indexOf will avoid the possible quote issue and possibly other odd browser quirks
    // switch true means it will do the first case it finds that evaluates to true
    switch(true)
    {
        // indexof means it looks through your string for the given substring
        // and returns the position so, "abc".indexOf("b") returns 1 (its 0 based)
        // if it doesnt find it anywhere it returns -1
        // so for our switch, it looks inside the backgroundImage string
        // url("../assets/x.png") no-repeat 50% 50%
        // or whatever it may be for the part "1.png"
        // if it finds it, it will return 5, or 8, or whatever the position is
        // if not it returns -1
        // so when this gets evaluated we check for "not -1"
        case (y.indexOf("1.png")!=-1):
          // if this case is true, then everything between the : and break;
          // will be performed, then it exits the switch
          y = 'url("../assets/2.png")';
          break;      
        case (y.indexOf("2.png")!=-1):
          y = 'url("../assets/3.png")';
          break;      
        case (y.indexOf("3.png")!=-1):
          y = 'url("../assets/4.png")';
          break;      
    }
}

使用 getElementsByName() 函数,在要更改的所有节点上设置相同的名称。

function add(x) {
  var elements = document.getElementsByName("somename");
  /* Iterate over the array and set the .style.* elements as needed */
}

http://www.w3schools.com/jsref/met_doc_getelementsbyname.asp

你似乎发现父节点正常。作为设置样式对象属性的替代方法,请考虑改为添加和删除类。一些简单的功能是:

var yourLib = {
  dom: {},
  util: {}
};
/* Check if an element has a particular class name
*/
yourLib.dom.hasClassName = function(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);
    var re = new RegExp('(^|''s+)' + cName + '(''s+|$)');
    return el && re.test(el.className);
}
/* Add a class name if element doesn't already have it
*/
yourLib.dom.addClassName = function(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);
    if (!yourLib.dom.hasClassName(el, cName)) {
        el.className = yourLib.util.trim(el.className + ' ' + cName);
    }
}
/* Remove a class name if element has it
*/
yourLib.dom.removeClassName = function(el, cName) {
    if (typeof el == 'string') el = document.getElementById(el);
    if (util.dom.hasClassName(el, cName)) {
        var re = new RegExp('(^|''s+)' + cName + '(''s+|$)','g');
        el.className = yourLib.util.trim(el.className.replace(re, ''));
    }
}
/* Remove leading and trailing whitespace and reduce
** multiple intermediate whitespaces to a single space
*/
yourLib.util.trim = function(s) {
  return s.replace(/(^'s+)|('s+$)/g,'').replace(/'s+/g,' ');
}

您的代码应该可以正常工作,除非您错误地匹配了现有背景图像。 它不会返回与您设置时相同的引号。

//When setting the url property, you need to wrap the actual URI in double quotes
//and then wrap the whole thing in single quotes to indicate to JS that it's a string
y.backgroundImage = 'url("../assets/1.png")'; //set background image
//y.backgroundImage now has a value of 'url(../assets/1.png)'    
//Here you try to match the value of y.backgroundImage against the string you
//originally stored in it, but that won't work
y.backgroundImage == 'url("../assets/1.png")'; //false
//The backgroundImage property returns a string that has the quotes stripped
//out of the inside of the URL definition
y.backgroundImage == "url(../assets/1.png)";  //true
好的

,所以我让它工作了,这是以后偶然发现这个的人的解决方案......

function add(x)
{
    var y = x.parentNode.style.backgroundImage;
    if ((y == '') || (y.indexOf("3_0.png") != -1))
        x.parentNode.style.backgroundImage = 'url(../_assets/3_1.png)';
    else if (y.indexOf("3_1.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_2.png)';
    else if (y.indexOf("3_2.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_3.png)';
    else if (y.indexOf("3_-3.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_-2.png)';
    else if (y.indexOf("3_-2.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_-1.png)';
    else if (y.indexOf("3_-1.png") != -1)
        x.parentNode.style.backgroundImage = 'url(../_assets/3_0.png)';
}

基本上,在WSkid的帮助下(谢谢!我使用"indexOf"来确定哪个是当前背景,并根据调用的函数相应地进行更改。这是加法函数的代码。