根据屏幕宽度更改JavaScript中的标签属性 [英] Change an a tag attribute in JavaScript based on screen width

查看:110
本文介绍了根据屏幕宽度更改JavaScript中的标签属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用媒体查询来更改标签的属性,但我发现具有超链接的媒体纯粹是建议性的。所以,另一种方法是使用JavaScript,但我似乎无法让screen.width工作。

I was trying to change the attribute of an a tag using media queries but I found out that media with a hyperlink is purely advisory. So, the alternative is to use JavaScript but I seem to be having trouble getting the screen.width to work.

JavaScript:

JavaScript:

function adjustHeight(){
    var actual_width=screen.width;
    alert("width: " + actual_width);
    if(actual_width < 1281) {
        var h1= document.getElementById('procsLink').getAttribute('font-size');
        alert("font-size: " + h1);
        h1 = 35px;
        document.getElementById('procsLink').setAttribute('<font></font>-size',h1)
    }
return false;
}

以下是我的Jsfiddle代码: http://jsfiddle.net/Arandolph01/2DVv9/

Here is my Jsfiddle of the code: http://jsfiddle.net/Arandolph01/2DVv9/

注意:I知道有一种方法可以让点击后链接仍然显示,以便您可以看到更改的属性。 (不知道如何)

Note: I know there is a way to have the link still appear after 'click' so you can see the changed attribute. (Not sure how)

为了让JavaScript识别屏幕大小,我需要做些什么?我的标签是否正确?

What do I need to do to get the JavaScript to recognize the screen size? Is my a tag correct?

谢谢。

推荐答案

这是问题,锚标记上没有标识,因此请调整您的html,如下所示:
- 将标识添加到锚标记
- 删除了实际链接,以便您可以看到标记更改字体大小
- 删除了onclick中的分号

Here is the problem, there is no id on that anchor tag so adjust your html like this: - added id to the anchor tag - removed the actual link so you can see the a tag change font size - removed the semicolon in the onclick

<span id="sigs" style="display: block;">
    <li >
        <a id="procsLink" href="#" onclick="adjustHeight()" class="sigsLink" >Manage Signatures</a>
    </li>
</span>

比你的css是这样的:

Than your css like this:

#procsLink{
    font-size: 14px;
}

和你的JS一样:

And your JS like this:

function adjustHeight(){

    var actual_width = window.innerWidth;

    if(actual_width < 1281) {
        var h1 = document.getElementById('procsLink');
        var newFontSize = '35px';
        h1.style.fontSize = newFontSize;
    }

}

这篇关于根据屏幕宽度更改JavaScript中的标签属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆