【问题标题】:Can I change placeholder text with CSS or jQuery depending on the browser width?我可以根据浏览器宽度使用 CSS 或 jQuery 更改占位符文本吗?
【发布时间】:2014-10-10 03:24:09
【问题描述】:

在我的 Bootstrap 顶部菜单(Rails 4 应用程序)中,我有一个搜索栏,用户可以在其中搜索产品,因此我的占位符文本类似于:

查找产品,例如Macbook Pro...

当浏览器被调整为例如小手机格式,文字太长。所以我希望文本只是这样的:

查找产品...

我正在使用 Rails 本地化,所以我希望能够拥有本地化的文本,而不是直接将某些内容放入 css 文件中。所以也许 jQuery 是可能的,尽管我认为它是一个更重的解决方案。有什么想法吗?

我的占位符 CSS 如下所示:

@media (max-width: 614px) and (min-width: 1px) {
  .top-menu input {
    width: 230px;
  }

  .top-menu input::-webkit-input-placeholder {
    color: #6b7279;
  }

  .top-menu input:-moz-placeholder {
    color: #6b7279;
  }

  .top-menu input:-ms-input-placeholder {
    color: #6b7279;
  }
}

【问题讨论】:

标签: jquery ruby-on-rails css twitter-bootstrap-3


【解决方案1】:

试试

$(function () {
    $(window).on("resize", function (e) {
        var w = e.target.innerWidth;
        var input = $("input[class=top-menu]");
        return input.css({
            "color": "#6b7279",
            "width": "230px"
            })
            .attr("placeholder"
                  , (w > 1 && w < 614) 
                  ? "Find a product..." 
                  : "Find product, e.g. Macbook Pro...")
    }).resize()
});

jsfiddle http://jsfiddle.net/guest271314/vfu3cdwb/4/

【讨论】:

    【解决方案2】:

    你可以做这样的事情。在这种情况下,.my_textarea 是附加到 textarea html 标记的类。

     $('.my_textarea').each(function() {
            $(this).data('placeholder', $(this).attr('placeholder'));
        });
    
        function changePlaceholder() {
            if( $(window).width() <= 640){
                $('.my_textarea').attr('placeholder','Find product...');
            } else {
                $('.my_textarea').each(function() {
                    $(this).attr('placeholder', $(this).data('placeholder'));
                });
            }   
        }
    
        $(window).resize( changePlaceholder ).trigger('resize');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-28
      • 2011-12-03
      • 2021-01-27
      • 2021-12-21
      • 1970-01-01
      相关资源
      最近更新 更多