LoginSignup
3
2

More than 5 years have passed since last update.

input要素のplaceholderを画像にしたい・textareaにもplaceholderを当てたい

Posted at

例えばこんなのに

index.html
<div class="input__wrapper">
    <textarea class="input"></textarea>
    <div class="input__placeholder">名前</div>
</div>

<div class="input__wrapper">
    <input type="text" class="input" />
    <div class="input__placeholder">名前</div>
</div>

placholderは別な要素として置いておきつつ、wrapperでinput,textareaを囲います。

style.css
.message__input__wrapper {
    position: relative;
    width: 100px;
    width: 50px;
    cursor: pointer;
}
.message__input {
    display: block;
    width: 100%;
    height: 100%;
    /*inputのスタイルをリセットする記述は省略*/
}
.message__input__placeholder {
    pointer-events: none;
    position: absolute;
    /*出したい画像と場所を設定*/
}

JSはjQueryが必要ですがこんな感じに書けばplaceholderと同じような挙動が出来ます。

script.js
$(".input").on("focus", () => {
    $(".input__placeholder").hide();
}).on("blur", () => {
    if (0 < $(".input").val().length) {
        $(".input__placeholder").hide();
    } else {
        $(".input__placeholder").show();
    }
});

//pointer-events非対応端末のために
$(".input__placeholder").on("click", () => {
    $(".input__placeholder").hide();
    $(".input").focus()
});

以上です。

3
2
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
3
2