注册账号登录
React操作DOM —— 添加查看原图按钮的图片点击事件+轮播
在componentDidMount中添加document的事件监听方法,代码如下:document.body.addEventListener('click', function(e) { // 判断是否点击的图片 i...

增加兼容火狐和可点击区域控制

getImg = () => {
const that = this
document.body.addEventListener('click', function(e) {
console.log(e, 'getimg')
// 火狐没有 e.path 属性
const isFF = /Firefox/.test(navigator.userAgent)
// 可点击区域
const elem = isFF ? e.rangeParent.id || e.rangeParent.parentNode.id : (e.path.filter(item => item.id === 'content')[0] || []).id
// 判断是否点击的图片
if (e.target.nodeName === 'IMG' && that.content && elem === 'content') {
let params = {}
params.param = {}
// 获取imglist
const oPics = that.content.getElementsByTagName('img')
params.param.imageArray = []
for (let i = 0; i < oPics.length; i++) {
params.param.imageArray.push({ url: oPics[i].src })
}
for (let i = 0; i < oPics.length; i++) {
// 判断点击图片的index
if (e.target.src === params.param.imageArray[i].url) {
params.param.index = i
}
}

that.setState({
imgObj: params.param,
showPic: true
})
}
})
}

jsx 增加一个ID 用来判断

const { imageArray = [], index } = imgObj
<div id="content" ref={e => (this.content = e)} styleName="article-content" dangerouslySetInnerHTML={{ __html: content }} />