teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

2

コードを追加

2021/08/29 01:57

投稿

itagagaki
itagagaki

スコア8402

answer CHANGED
@@ -6,4 +6,41 @@
6
6
 
7
7
  ---
8
8
 
9
- (追記)このアプローチは画像のオリジナルサイズと`background-size`から表示サイズを自分で計算してみているわけで、必ずしもブラウザ(レンダリングエンジン)の結果とぴったり一致するとは限らない、という問題はありますね。用途によると思いますが。
9
+ (追記)このアプローチは画像のオリジナルサイズと`background-size`から表示サイズを自分で計算してみているわけで、必ずしもブラウザ(レンダリングエンジン)の結果とぴったり一致するとは限らない、という問題はありますね。用途によると思いますが。
10
+
11
+ ---
12
+
13
+ コードの間違いをFixしてみました。
14
+
15
+ ```jQuery
16
+ function getBackgroundSize(selector, callback) {
17
+ var img = new Image(),
18
+ // here we will place image's width and height
19
+ width, height,
20
+ // here we get the size of the background and split it to array
21
+ backgroundSize = $(selector).css('background-size').split(' ');
22
+
23
+ // checking if width was set to pixel value
24
+ if (/px/.test(backgroundSize[0])) width = parseInt(backgroundSize[0]);
25
+ // checking if width was set to percent value
26
+ if (/%/.test(backgroundSize[0])) width = $(selector).width() * (parseInt(backgroundSize[0]) / 100);
27
+ // checking if height was set to pixel value
28
+ if (/px/.test(backgroundSize[1])) height = parseInt(backgroundSize[1]);
29
+ // checking if height was set to percent value
30
+ if (/%/.test(backgroundSize[1])) height = $(selector).height() * (parseInt(backgroundSize[1]) / 100);
31
+
32
+ img.onload = function () {
33
+ // check if width was set earlier, if not then set it now
34
+ if (typeof width == 'undefined') width = this.width;
35
+ // do the same with height
36
+ if (typeof height == 'undefined') height = this.height;
37
+ // call the callback
38
+ callback({ width: width, height: height });
39
+ }
40
+ // extract image source from css using one, simple regex
41
+ // src should be set AFTER onload handler
42
+ img.src = $(selector).css('background-image').replace(/url(['"]*(.*?)['"]*)/g, '$1');
43
+ }
44
+ ```
45
+
46
+ そして `getBackgroundSize("#backg", (size) => alert(size.width + "," + size.height));` を試したら 25,25 と出ました。

1

追記

2021/08/29 01:57

投稿

itagagaki
itagagaki

スコア8402

answer CHANGED
@@ -2,4 +2,8 @@
2
2
 
3
3
  [javascript — JavaScriptを使用してCSS背景画像のサイズを取得しますか?](https://www.it-mure.jp.net/ja/javascript/javascript%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6css%E8%83%8C%E6%99%AF%E7%94%BB%E5%83%8F%E3%81%AE%E3%82%B5%E3%82%A4%E3%82%BA%E3%82%92%E5%8F%96%E5%BE%97%E3%81%97%E3%81%BE%E3%81%99%E3%81%8B%EF%BC%9F/969780680/)
4
4
 
5
- ここに書き残されている`getBackgroundSize`をちょっと試してみたところ、まずjQueryが必要なのと、ちょっとバグがあるのか正しい結果が得られなかったんですが、アプローチは良さげですので、このコードをベースに修正してみるのもいいかと思います。
5
+ ここに書き残されている`getBackgroundSize`をちょっと試してみたところ、まずjQueryが必要なのと、ちょっとバグがあるのか正しい結果が得られなかったんですが、アプローチは良さげですので、このコードをベースに修正してみるのもいいかと思います。
6
+
7
+ ---
8
+
9
+ (追記)このアプローチは画像のオリジナルサイズと`background-size`から表示サイズを自分で計算してみているわけで、必ずしもブラウザ(レンダリングエンジン)の結果とぴったり一致するとは限らない、という問題はありますね。用途によると思いますが。