5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ElectronからCSSのurl()を動的に使う場合の注意点

Last updated at Posted at 2016-03-18

概要

JSからelement.style.backgroundImageなどを設定するとき、
画像のパスを普通に
require("path").resolve('../image/hoge.jpg')

__dirname + '/image/hoge.jpg'
url()に渡すと失敗する

結論

(Windowsでは)__dirnameのパスの取得やrequire("path").resolve()による相対パスの解決後のパスの区切りは\
しかし、CSSのurl()では\をエスケープとみなすので/に置換しなければならない
つまり

element.style.backgroundImage = 'url(' + require("path").resolve(path).replace(/\\/g, '\/') + ')'

としなければCSSは正しいパスを解釈しない。

検証環境

  • Windows7 Professional 64bit
  • electron-prebuilt 0.36.4
  • node v5.2.0
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?