2

我目前正在开发一个响应式网站。我开发了一个 jquery 脚本来更改链接中的 href 属性。

$("a.modal").attr("href", "https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0")

它工作得很好 - 但我希望它只针对屏幕宽度小于 767 像素的设备(移动设备)。

这个脚本应该可以工作,但我真的不能让它工作。

<script type="text/javascript">
$(document).ready(function(){
if ($(window).width() < 767) {
$("a.modal").attr("href", "https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0")
}
});
</script>

链接到网页。

http://visbyfangelse.se.linweb63.kontrollpanelen.se/rum-priser/

它是我要更改的粉红色按钮的链接。

4

3 回答 3

6

实际上,问题在于您的其余代码。为你让我挖掘它而感到羞耻。:P

$('a[name=modal]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    // etc etc.

因此,您会因为 preventDefault 而阻止 href 触发。为什么不在这里打补丁:

$('a[name=modal]').click(function(e) {
    //Cancel the link behavior
    e.preventDefault();
    if ($(window).width() < 767)
    {
        // I'm assuming you'd get this dynamically somehow;
        location.href="https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0";
        return;
    }
    // etc etc.

已添加 | 帮助 OP 使他的项目工作的功能全文:

$('a[name=modal]').click(function(e) {
    //Cancel the link behavior

    e.preventDefault();
    if ($(window).width() < 767)
    {
        // I'm assuming you'd get this dynamically somehow;
        location.href="https://secured.sirvoy.com/book.php?c_id=1602&h=ea3a7c9286f068fb6c1462fad233a5e0";
        return;
    }
    //Get the A tag
    var id = $(this).attr('href');

    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    //Set height and width to mask to fill up the whole screen
    $('#mask').css({'width':maskWidth,'height':maskHeight});

    //transition effect     
    $('#mask').fadeIn(1000);    
    $('#mask').fadeTo("slow",0.8);  

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();


    //transition effect
    $(id).fadeIn(2000); 

});
于 2012-04-17T08:15:14.597 回答
0

你可以使用window.matchmedia

if (window.matchMedia("(max-width:768px)").matches) {
   $("a.modal").attr("href", "...");
}

有关兼容性列表,请参阅http://caniuse.com/matchmedia

于 2012-04-17T08:12:07.773 回答
0

此脚本将帮助您检测所有浏览器的屏幕尺寸

var viewportwidth;
var viewportheight;

//Standards compliant browsers (mozilla/netscape/opera/IE7)
if (typeof window.innerWidth != 'undefined')
{
    viewportwidth = window.innerWidth,
    viewportheight = window.innerHeight;
}

// IE6
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth !=
'undefined' && document.documentElement.clientWidth != 0)
{
    viewportwidth = document.documentElement.clientWidth,
    viewportheight = document.documentElement.clientHeight;
}

//Older IE
else
{
    viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
    viewportheight = document.getElementsByTagName('body')[0].clientHeight;
}

警报(视口宽度+“〜”+视口高度);

于 2013-09-05T06:30:42.140 回答