How to create dynamic diagonal line from left-bottom to right-top corner?

眉间皱痕 提交于 2019-12-02 21:12:43

Use trigonometry to compute the desired angle:

var angle = Math.atan2($(window).width(),$(window).height()); // in radians
$('#blocktop,#blockbottom').css('transform','skew(-'+angle+'rad)');

(Note for math geeks and other pedants: the arctangent would normally take the height divided by the width, not the other way around. In this case, however, we're skewing a vertical line instead of a horizontal one, so the above code gives the desired result.)

Note that newer versions of jQuery will automatically add the necessary -webkit- or -moz- prefix to that CSS transform property.

You might also want to display:none the elements until the above code can alter the angle, and then show() them immediately after the angle is computed:

$('#blocktop,#blockbottom').css('transform', 'skew(-' + angle + 'rad)')
    .add('#logo').show();

http://jsfiddle.net/mblase75/6a93T/10/

I just use the fact that a DOM-Element with two different border for top and right results in a diagonal line where both meet. Then put the height and width of the DOM-Element to zero and set the border-top-width to window-height and the border-right-width to window-width. Update it with JavaScript on resize... That's all.

I've put a container in the DOM

<div id="diagonal_outer"><div id="diagonal"></div></div>

Following CSS is nessesary

div#diagonal_outer {
    position: fixed !important;
    position: absolute;
    overflow: hidden;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    z-index: -100;
}
div#diagonal {
    position: relative;

    border-color: #FAE9E1 #ffffff;
    border-style: solid;
    border-left-width: 0;       
    border-top-width: 10240px;
    border-right-width: 12800px;
    border-bottom-width: 0;

    height: 0;
    width: 0;

    left: 50%;
    top: 50%;
    margin-left: -6400px; /* half of border-right-width */
    margin-top: -5120px; /* half of border-top-width */

    z-index: -100;
}

and following JavaScript to actualize on resize

jQuery(document).ready(function() {
    diagonal();
});

jQuery(window).resize(function() {
    diagonal();
});

var diagonal = function() {
    var wWidth = jQuery(window).width();
    var wHeight = jQuery(window).height();

    jQuery('#diagonal').css('left', 0);
    jQuery('#diagonal').css('top', 0);
    jQuery('#diagonal').css('margin-left', 0);
    jQuery('#diagonal').css('margin-top', 0);

    jQuery('#diagonal').css('border-right-width', wWidth);
    jQuery('#diagonal').css('border-top-width', wHeight);
};

OK, the solution with CSS-skew is nice, but this one works with CSS <3

You don't have to do too much for this. See demo here

HTML

<div class="diagonal"></div>

CSS

.diagonal {
    width: 0; 
    height: 0; 
    border-top: 110px solid transparent;
    border-right:110px solid blue; 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!