0%

Vue 设置 iframe 内容中的样式

这是建立在同源的前提下的

1
<iframe v-if="$attrs.visible" ref="iframe" :src="iframeUrl" width="100%" height="100%" frameborder="0" :class="$style.iframe" @load="iframeLoaded" />
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// The real load method
iframeLoaded () {
this.iframeReady = false

const document = this.$refs.iframe.contentWindow.document
if (!document) return
console.log(`document`, document)
const styleElem = document.createElement('style')

styleElem.innerHTML = `
::-webkit-scrollbar {
width: 7px;
height: 5px;
border-radius:15px;
-webkit-border-radius: 15px;
}
::-webkit-scrollbar-track-piece {
background-color: #ffff;
border-radius:15px;
-webkit-border-radius: 15px;
}
::-webkit-scrollbar-thumb:vertical {
height: 5px;
background-color: rgba(144, 147, 153, 0.5);
border-radius: 15px;
-webkit-border-radius: 15px;
}
::-webkit-scrollbar-thumb:horizontal {
width: 7px;
background-color: rgba(144, 147, 153, 0.5);
border-radius: 15px;
-webkit-border-radius: 15px;
}
`
document.head.appendChild(styleElem)

console.log('iframe loaded')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
<style module lang="scss">
.iframe {
border:none;
body {
::-webkit-scrollbar-thumb {
background-color: #EFEFF0;
border: 1px solid transparent;
background-clip: padding-box;
border-radius: 5px;
}
}
}
</style>