问题
I have a slider like this:
It is written by angular-js, the code is as below:
<div class="ng-isolate-scope" data-range-slider-directive="" data-model="dataModel" data-model-property="surroundingEvnt" data-floor-value="0" data-ceil-value="10" data-max-value-plus="true">
<div class="rzslider ng-isolate-scope" data-rz-slider-model="model[modelProperty]" data-rz-slider-options="slider.options">
<span class="rz-bar-wrapper">
<span class="rz-pointer rz-pointer-min" ng-style="minPointerStyle" role="slider" aria-valuenow="0" aria-valuetext="0" aria-valuemin="0" aria-valuemax="10" tabindex="0" style="left: 0px;"></span>
// a lot of spans here
</div>
</div>
This is the plugin: https://github.com/angular-slider/angularjs-slider
I want to click to slide the slider-point to the value, for example 4 or 6. But I don't know how to move the slider. Can anybody have any suggestions. My tests are written in Java. Thanks
回答1:
You didn't specify the language you wanted so I've written some code in Java that hopefully you can use or adapt. The concept is get the container element for the slider and then click (once) on the element based on a scale factor for the width to get the desired value.
I found an example angular.js slider on this page that I used to write this code and it's working. First we have a function that takes the value to be set and the WebElement for the slider. The function uses the width of the slider element and the min/max values of the slider to determine the scale and click the correct offset to set the correct value.
/**
* Sets the value on a horizontal angular.js slider
*
* @param value
* the desired value
*/
public static void setHValue(WebElement slider, double value)
{
double minValue = Double.parseDouble(slider.getAttribute("min"));
double maxValue = Double.parseDouble(slider.getAttribute("max"));
int sliderH = slider.getSize().height;
int sliderW = slider.getSize().width;
System.out.println(sliderH);
System.out.println(sliderW);
Actions action = new Actions(driver);
action.moveToElement(slider, (int) (value * sliderW / (maxValue - minValue)), sliderH / 2).click().build().perform();
}
Calling it would look something like this.
driver.get("https://material.angularjs.org/latest/demo/slider");
WebElement slider = driver.findElement(By.id("red-slider"));
setHValue(slider, 150);
This slider has a value range of 0-255 so to get the desired value of 150 we get the min and max values from the element itself and then determine the scale factor for the width based on the width of the element to determine the width offset. The height offset is just half of the height of the element which assumes that the slider is in the middle of the element. All that's left after that is to use the .moveToElement(toElement, xOffset, yOffset) method of Actions and click the correct location.
来源:https://stackoverflow.com/questions/40549897/set-value-for-slider-with-selenium-webdriver