亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 forEach 與 e.target.children 一起工作

為什么 forEach 與 e.target.children 一起工作

Cats萌萌 2021-08-20 19:14:30
我有一個包含多個顏色元素的 SVG/按鈕。這個想法是讓元素在 mouseEnter 上一個一個地滑入,然后在 mouseLeave 上從另一側離開,然后重置以便再次執行。使用 [...e.target.children] 創建數組時,后續的 forEach 函數正常工作。使用 getElementById 并轉換為數組時,出現錯誤“不是函數。前者返回一個實際元素的列表,而后者只返回一個列表。如何正確轉換數組以便 forEach 函數工作?<svg id="HeroButton" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 270 48">  <title>HeroButton</title>  <polygon className="pink" points="29 23 52 0 15 0 0 0 0 48 15 48 54 48 29 23" fill="#ed3e88"/>  <polygon className="yellow" points="97.5 40.5 114 24 96 24 96 0 52 0 29 23 54 48 82 48 82 40.5 97.5 40.5" fill="#fded52"/>  <polygon className="turq" points="155.5 19.5 175 0 116 0 96 0 96 24 114 24 97.5 40.5 82 40.5 82 48 116 48 156.5 48 185 19.5 155.5 19.5" fill="#17adcb"/>  <polygon className="beige" points="224.5 33 224.5 13.5 238 0 189 0 175 0 155.5 19.5 185 19.5 156.5 48 189 48 239.5 48 224.5 33" fill="#ffffc7"/>  <polygon className="turq2" points="243 0 238 0 224.5 13.5 224.5 33 239.5 48 243 48 270 48 270 0 243 0" fill="#17adcb"/></svg>export default class HeroButton extends React.Component {  constructor(props) {    super(props);    this.state = {      translate: "translateX(100%)",      opacity: 1    }  };  componentDidMount() {    // const polygons = [...document.getElementById('HeroButton').children;    const polygons = Array.from(document.getElementById('HeroButton').children);    console.log({polygons})    this.updatePolygons(polygons);    this.setState({      translate: "translateX(-100%)",      opacity: 0    });  };  handleMouseEnter = (polygons) => {    this.updatePolygons(polygons)  };  handleMouseLeave = (polygons) => {    this.setState({      translate: "translateX(100%)",      opacity: 1    });  };  updatePolygons = (polygons) => {    // const polygons = [...e.target.children];    polygons.forEach(child => {      child.style.transform = this.state.translate;      child.style.opacity = this.state.opacity;    });
查看完整描述

2 回答

?
有只小跳蛙

TA貢獻1824條經驗 獲得超8個贊

口香糖,您可以將孩子放在不同的數組中,然后可以在該數組上使用 forEach。

const el = document.getElementsByClassName('js-favorite-btn s-btn s-btn__unset c-pointer py8')

使用 el[0].children.forEach 時出現錯誤

el[0].children.forEach is not a function

但是當使用

const arr = [el[0].children]

然后運行 forEach 工作。我希望這對你有用。


查看完整回答
反對 回復 2021-08-20
  • 2 回答
  • 0 關注
  • 231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號