【问题标题】:JavaScript TypeError: says a CSS declaration returns as "null"JavaScript TypeError:说 CSS 声明返回为“null”
【发布时间】:2022-01-14 18:49:39
【问题描述】:

以下是似乎引起问题的代码:

        player.style.height = playerH + "px";
        function trackXY(){
        for(let i=0; i<pokeS.length; i++){
        let pokeS = document.getElementsByClassName('pikaStyle' + i);
        let xPlayer = parseInt(player.style.left + .5*player.style.width);
        let yPlayer = parseInt(player.style.top + .5*player.style.height);
        let xpokeS = parseInt(pokeS.style.left + .5*pokeS.style.width);
        let ypokeS = parseInt(pokeS.style.top + .5*pokeS.style.height);
        let rPlayer = .5*parseInt(player.style.height);
        let rpokeS = .5*parseInt(pokeS.style.height);
        let dX = xpokeS - xPlayer;
        let dY = ypokeS - yPlayer;
        let distance = Math.sqrt((dX*dX)+(dY*dY))
        if(distance <= (rpokeS+rPlayer)){
            alert("collison!" + pokeS.id);
        player.style.height = parseInt(player.style.height) + .5*parseInt(pokeS.style.height);
        }
      }
    }

它总是返回“样式”无法读取或“左”未定义。有人可以建议吗?谢谢。

【问题讨论】:

  • 想知道我的回答是否能解决您的问题:) ?
  • 好的,非常感谢!!

标签: javascript css function


【解决方案1】:

您应该使用window.getComputedStyle()getPropertyValue 来获取样式。你不能直接使用element.style.height,它不会返回任何东西。

Window.getComputedStyle() 方法在应用活动样式表并解析这些值可能包含的任何基本计算后,返回一个包含元素所有 CSS 属性值的对象。

在您的代码中,使用:

window.getComputedStyle(player).getPropertyValue('height') 
window.getComputedStyle(pokeS).getPropertyValue('height')

例子:

let div = document.querySelector('div')
//return nothing
//console.log( div.style.height)
console.log(window.getComputedStyle(div).getPropertyValue('height'))
div{
height:50px;
}
&lt;div&gt;&lt;/div&gt;

【讨论】:

    猜你喜欢
    • 2016-05-11
    • 2019-07-18
    • 2016-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多