[英]Change link text based on browser width
我有一個鏈接,當瀏覽器的寬度降至40em以下時,我想將內容“ Post Your Need”更改為“✎”。 我已經嘗試了一個半小時的谷歌搜索,但無濟於事。 這里有什么幫助嗎? 我在尋找jquery / javascript。
<a class="postbutton" href='post.php'>Post Your Need</a>
編輯:
所有人的堅持讓我考慮使用CSS而不是jquery。 最后,我用鉛筆圖標創建了第二個錨標記,並使用媒體查詢將其放置在視口上方。 因此,當它越過查詢行時,較大的標簽將以“ margin-top:-2em”向上移動,而較小的則向下移動。 它非常簡單,允許我將單獨的CSS規則應用於這兩個元素,並且在調整瀏覽器大小時,上下移動它們看起來很酷。
您可以通過單獨的CSS( 示例 )來實現:
@media (max-width: 40em) {
// when smaller than 40em...
.postbutton {
// resize postbutton... hiding overflow
display: inline-block;
white-space: nowrap;
overflow-x: hidden;
width: 13px;
color: #000000;
text-decoration: none;
}
.postbutton:before{
// and insert this text at the beginning
content: '✎';
}
}
另外,從語義上講,您可以更改標記和CSS。 只需使用以下標記( sample )替換<a class="postbutton">
的內容:
<span class="collapsed">✎</span><span class="expanded">Post Your Need</span>
然后,您可以使用CSS專門定位這些元素:
.postbutton .collapsed
{
// hide the collapsed text by default
display: none;
}
@media (max-width: 40em) {
// when smaller than 40em...
.postbutton .collapsed {
display: inherit; // show the collapsed text
}
.postbutton .expanded {
display: none; // hide the expanded text
}
}
參見:before
偽元素和CSS Media Queries
正如代號所說的那樣,有一個簡單的css選項:媒體查詢( https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries )
但是如果您設置使用jquery,則可以通過執行以下操作來獲取窗口的寬度:
$(window).width(); // returns the width of the window
// do stuff when the window is resized
$(window).resize(function () {
$(window).width(); // the new width
});
不知道我嘗試在em中獲取Browser寬度的方法是否可行...但是為什么不以px為單位呢?
var minWidth = 40; // Define minWidth
$(window).resize(function() {
// Get Browser width in em
var w = $(window).width() / parseFloat($("body").css("font-size"));
// Compare Browser width to defined minWidth
if(w < minWidth) {
// If Browser window is smaller than the defined minWidth, set small Link Text
$(".linkClass").html("[new HTML Content]");
} else {
// If Browser window is bigger or equal to minWidth, set big Link Text
$(".linkClass").html("Post your need");
}
}
注意:未經測試,可能需要一些調整
編輯:哎呀... 40em不是30 :-)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.