LoginSignup
0
0

More than 1 year has passed since last update.

HTMLで広告をPC・スマホ(SP)で場所をわけて置く方法

Posted at

TL;DR

ブログとかで広告を置くとき、広告の位置をスマホ版とパソコン版で分けたいときってありますよね?
そういうときは、よくJavascriptを使うのですが、どうやるのかがわからない人のために書き残しておきます。

手順

1. Javascriptのコードをつくる

まず、Javascriptのコードを作ります。

/* Settings */
/* Set class name */
const adssp = document.getElementsByClassName('ads-sp'); /* for SmartPhone */
const adspc = document.getElementsByClassName('ads-pc'); /* for PC */
/* Set HTML */
const html = '<script src="https://aas.information-portal.net/tag.php?invid=00"></script>'

/* Main Code */
if (window.matchMedia && window.matchMedia('(max-device-width: 640px)').matches) {
    for (i = 0; i < adssp.length; i++) {
        var adstag = document.createElement("iframe");
        adssp[i].appendChild(adstag);
    }
} else {
    for (i=0; i < adspc.length; i++) {
        var adstag = document.createElement("iframe");
        adspc[i].appendChild(adstag);
    }
}
adstag.style.border = "none"
adstag.style.width = "300px"
adstag.style.height = "250px"
adstag.contentWindow.document.open();
adstag.contentWindow.document.write(html);
adstag.contentWindow.document.close()

途中のSet HTMLコメントの直下にある変数は広告のhtmlタグにしてください。
また、

adstag.style.width
adstag.style.height

は広告のサイズにしてください。

2. HTMLにjsを埋め込む

HTMLのbodyタグの一番最後に

<script src="https://linuxcodevserver.github.io/javascript/main.js"></script>

と埋め込みます。

3. 広告を置きたい場所を指定する

広告を置きたい場所にはこのようなコードを置きます。

<div class="ads-sp"></div> <!-- スマートフォンの場合 -->
<div class="ads-pc"></div> <!-- PCの場合 -->
0
0
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
0
0