注册账号登录
plain
话是空的,只有行动才有意义
关注

React操作DOM —— 添加查看原图按钮的图片点击事件+轮播

在componentDidMount中添加document的事件监听方法,代码如下:

document.body.addEventListener('click', function(e) {
// 判断是否点击的图片
if (e.path[0].nodeName === 'IMG') {
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.path[0].src === params.param.imageArray[i].url) {
params.param.index = i
}
}
console.log(params)
that.setState({
imgObj: params.param,
showPic: true
})
}
})

render

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

添加(swipe)比较简单的swipe,包很小

{showPic ? (
<div styleName="article-slide" onClick={this.closePic}>
<Swiper Pagination={true} Controller={true} Start={index}>
{imageArray.map((item, index) => (
<div className="swipe-item" key={item.url + index}>
<img src={item.url} />
</div>
))}
</Swiper>
</div>
) : null}

附加Swiper 插件链接:https://github.com/dxhuii/react-zanpian/blob/master/src/app/components/Swiper/index.js

使用些功能的页面:https://github.com/dxhuii/react-zanpian/blob/master/src/app/pages/article/index.js

2条评论

再加个演示地址吧:https://www.5ddm.com/article/3030

回复

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

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 }} />
回复
plain
话是空的,只有行动才有意义
关注私信
1
关注
6
粉丝
22
帖子