前言
公司让我修改iframe的原生pdf样式,刚开始写的时候是真的烦,花了几天时间总算是完成了。
原ifmame标签
<iframe ref={this.iframeRef} id="pdf-ifr" src={pdfurl} className={'w-full h-full'} />
1. 修改内部样式
1. 获取DOM修改
componentDidMount(): void {
this.onload()
}
const pdfIfr = document.getElementById('pdf-ifr') as HTMLIFrameElement
pdfIfr.onload = () => {
const iframeWindow = pdfIfr?.contentDocument || pdfIfr?.contentWindow?.document
// 直接修改内置样式,类似于内敛样式,只不过单独拆出来,不如直接插入css表直观
if (iframeWindow) {
const zoomOut = iframeWindow.querySelector('#zoomOut') as HTMLDivElement
zoomOut.style.border = '1px solid #F3F3F3'
zoomOut.style.marginRight = '6px'
zoomOut.style.background = '#fff'
}
2. 插入css样式
// 想修改其所有样式需要给style添加一个css样式表,类似于css格式
const pdfIfr = document.getElementById('pdf-ifr') as HTMLIFrameElement
pdfIfr.onload = () => {
const iframeWindow = pdfIfr?.contentDocument || pdfIfr?.contentWindow?.document
const style: any = iframeWindow?.createElement('style')
style.textContent = `
::-webkit-scrollbar {
width: 10px; /* 滚动条宽度 */
}
::-webkit-scrollbar-track {
background: #F1F1F1; /* 滚动条背景色 */
}
#thumbnailView::-webkit-scrollbar-track {
background: #fff; /* 滚动条背景色 */
}
::-webkit-scrollbar-thumb {
background: #9B9B9B; /* 滚动条滑块颜色 */
border-radius: 50px;
}
::-webkit-scrollbar-thumb:hover {
background: #9B9B9B; /* 滚动条滑块悬停颜色 */
}
.thumbnail.selected{
border-radius: 4px 4px 4px 4px;
border-color:#6BBCF6 !important;
border: 2px solid #6BBCF6;
transform: scale(1.2);
}
`
iframeWindow?.head.appendChild(style)
2. 内部方法
要点:获取iframeDOM ,我的是react代码
1.类组件
iframeRef: any
constructor(props: Props) {
super(props)
this.iframeRef = React.createRef()
}
<iframe ref={this.iframeRef} id="pdf-ifr"src={pdfUrl} className={'w-full h-full'} />
// 放大pdf
this.iframeRef.current.contentWindow.PDFViewerApplication.zoomIn()
// 缩小pdf
this.iframeRef.current.contentWindow.PDFViewerApplication.zoomOut()
// 下载pdf
this.iframeRef.current.contentWindow.PDFViewerApplication.download()
2. 函数组件
const iframeRef = useRef(null)
<iframe ref={iframeRef} id="pdf-ifr"src={pdfUrl} className={'w-full h-full'} />
// 放大pdf
iframeRef.current.contentWindow.PDFViewerApplication.zoomIn()
// 缩小pdf
iframeRef.current.contentWindow.PDFViewerApplication.zoomOut()
// 下载pdf
iframeRef.current.contentWindow.PDFViewerApplication.download()
3. 提示
非pdf格式的iframe应该也有对应的方法,需要自己去查