返回博客

Vue 设置 iframe 内容样式

在 Vue 中,如何设置 iframe 内容的样式,这篇文章介绍了如何在同源策略下,通过 JavaScript 在 iframe 加载后动态添加样式,解决 iframe 内容样式设置的问题。

Mt.r
|

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

<iframe v-if="$attrs.visible" ref="iframe" :src="iframeUrl" width="100%" height="100%" frameborder="0" :class="$style.iframe" @load="iframeLoaded" />
// 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')
}
<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>