【问题标题】:Change text when screen width is less than amount not working当屏幕宽度小于数量时更改文本不起作用
【发布时间】:2021-07-14 04:56:48
【问题描述】:

我正在尝试在屏幕尺寸小于 650 时更改此网站上的文本,但它不起作用。我尝试了Do something if screen width is less than 960 pxResizing images when screen is less than 1024 pixels width 的答案,但没有奏效。 Here是replit的链接,下面也是sn -p的代码。

if ($(window).width() < 650) { // I've also tried (window).width() and window.width
var words = $('.words');
words.text("Hello! This is the new text!");
}
else { 
}


<div class="intro">
  <div>
    <h1 class="ele">Hey there!</h1>
    <p class="ele words">Hi! This is the old text."</p>
  </div>
  <img class="ele me" src="me.png" alt="A picture of myself.">
</div>

【问题讨论】:

  • 你做了什么来调试你的代码?你有没有添加任何console.logs?还是穿越? $(window).width() 的值是多少? $(".words").length 的值是多少?您的代码是否在 HTML 之前运行?尝试将您的代码放入doc.ready。在jsfiddle 中工作正常,但最后运行 js 代码。不是每个人都会注册使用“replit”。
  • 旁注,你真的应该看看 CSS Media Queries developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/…
  • 你希望它只触发一次还是在调整屏幕大小时触发?

标签: javascript jquery


【解决方案1】:

我在 CodePen 上尝试了您的代码,它似乎工作正常,可能是您的脚本加载到了错误的位置,或者您尝试更改的元素尚未创建,也许更多代码可以提供帮助 see the example

<div class="intro">
  <div>
    <h1 class="ele">Hey there!</h1>
    <p class="ele words">Hi! This is the old text."</p>
  </div>
  <img class="ele me" src="me.png" alt="A picture of myself.">
</div>
$(window).resize(function() {
  if ($(window).width() < 650) {
    var words = $('.words');
    words.text("Hello! This is the new text!");
    }
    else { 
      var words = $('.words');
    words.text("Hello! This is the old text.");
  }
})

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    相关资源
    最近更新 更多