js实现 textArea 的 placeholder 换行

今天写textarea的placeholder 换行的方法,网络上找了好多资料,写的不太详细,只好自己写一个demo,现分享给大家。
网络上看到方法大概有jQuery的watermark,这种方法可以在chrome中实现,其他浏览器不可以,所以我选择用js实现以下。
要点:
1,鼠标的焦点事件focus与blur;
2,jQuery的input与propertychange事件;
当触发这些事件的时候改变textarea的value值;就这么简单,上代码了,拿下来就能用。

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <script src="js/jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
        <style>
            textarea {
                width: 675px;
                height: 150px;
                display: block;
                margin-left: 30px;
            }
        </style>
    </head>

    <body>
        <textarea id="text" maxlength="500"></textarea>
        <script>
            var placeholder = '1.儿童出行只含车位费,不含住宿费及门票等费用儿童门票不接受预定,请至景区门口自行购买。\n2.儿童车票与成人同价,如您的小孩不足80厘米,且不需要占车位,请在选择人数时不要提交儿童人数,如身高为80厘米以上的儿童必须提交儿童人数。\n3.如您的小孩身高超过120厘米请直接选择成人价,景区对特定人群有门票优惠政策参考温馨提醒';
            $('#text').val(placeholder).css({
                color: '#ccc'
            });
            $('#text').focus(function() {
                if($(this).val() == placeholder) {
                    $(this).val('').css({
                        color: '#ccc'
                    })
                } else {
                    $(this).css({
                        color: '#333'
                    })
                }
            });
            $('#text').blur(function() {  
                if($(this).val() == '') {  
                    $(this).val(placeholder).css({
                        color: '#ccc'
                    })
                }
            });
            $(document).on('input propertychange', '#text', function(event) {
                if($(this).val() == placeholder) {
                    $(this).val('').css({
                        color: '#ccc'
                    })
                } else if($(this).val() == "") {
                    $(this).val(placeholder).css({
                        color: '#ccc'
                    }).blur();
                } else {
                    $(this).css({
                        color: '#333'
                    })
                }
            })
        </script>
    </body>

</html>

猜你喜欢

转载自www.cnblogs.com/homehtml/p/12217580.html